从文件中的数据结构写入字符串

该程序应该由用户接收一些输入字符串,将它们保存在数据结构中,然后将所有内容打印到文件中。 对于exaple,如果我输入“test one”,它应该保存在inputs.one上,然后我应该在clients.txt上看到“test one”。 如果我输入“test one”,“test two”和“test three”,我应该看到在clients.txt上打印的那三个输入。

问题是,程序现在只执行一次scanf而不是三次,这就是为什么我添加了三个scanf而不是只进行一次scanf。 基本上,如果我输入“测试一个”它只会保存并打印测试一个,而不需要另外两个输入,我不知道为什么。

额外:我添加了这些fgets作为另一种尝试正确保存输入的方法,问题是fgets会将文件上的数据打印为

“测试一次测试两次测试三次”

而不是一条线上的所有东西,所以fgets也不会工作。

#include  #include  #include  struct inputs { char one[30]; char two[30]; char three[30]; }; int main(void) { struct inputs inputs = {"", "", ""}; FILE *cfPtr; // cfPtr = clients.txt file pointer // fopen opens file. Exit program if unable to create file if ((cfPtr = fopen("clients.txt", "w")) == NULL) { puts("File could not be opened"); } else { puts("Enter one, two, three."); puts("Enter EOF to end input."); printf("%s", "? "); //scanf("%[^\n]s%[^\n]s%[^\n]s", inputs.via, inputs.nome, inputs.stars); /* fgets(inputs.one, 30, stdin); fgets(inputs.two, 30, stdin); fgets(inputs.three, 30, stdin); */ while (!feof(stdin)) { scanf("%[^\n]s", inputs.one); scanf("%[^\n]s", inputs.two); scanf("%[^\n]s", inputs.three); fprintf(cfPtr, "%s%s%s", inputs.one, inputs.two, inputs.three); } fclose(cfPtr); // fclose closes file } }