我正在尝试接收一串用户输入并将其写入文件。但是,无论我做什么,输出总是从字符串中删除空格。
我认为使用gets()
/ puts()
的全部目的是它会读取/输出字符串中的所有字符,直到遇到换行符。
有人可以告诉我我做错了吗?
int main (void){
char userInput[100];
char filename[50];
FILE *cfPtr;
printf("Enter name of file to open: ");
scanf("%s", &filename);
cfPtr = fopen(filename, "a+");
printf("Enter text to add to file: \n");
fgets(userInput, 100, stdin);
while (strcmp( userInput, "0") != 0) {
fputs( userInput, cfPtr);
fgets(userInput, 100, stdin);
} // end while
fclose( cfPtr );
system("pause");
} // end main
答案 0 :(得分:3)
有人可以告诉我我做错了吗?
我注意到的第一个错误是在scanf中,对于使用%s
&
的字符串:
scanf("%s", &filename);
^
|
remove it, undefined behavior
应该只是:
scanf("%s", filename);
此后您的代码将无效。我找不到任何其他语法错误,所以我认为这是代码中的主要错误。
答案 1 :(得分:1)
1)fgets()和fputs()不会删除字符串中的任何空格。
2)一个潜在的“问题”是fgets()将保留“输入”字符,您可能不会将其视为字符串的一部分。
3)你的代码中的问题可能是你的“scanf()” - 你应该传递“filename”(这是一个数组),而不是“& filename”(这是重复的冗余)。
4)更好的是,您可以考虑将“fgets()”替换为“scanf()”。
... IMHO
PS: 这是使用fgets()和朋友的一个很棒的链接:
答案 2 :(得分:0)
这在g ++和linux下运行。
int main (void){
char userInput[100];
char filename[50];
FILE *cfPtr;
printf("Enter name of file to open: ");
scanf("%s\n", filename);
cfPtr = fopen(filename, "a+");
printf("Enter text to add to file: \n");
fgets(userInput, 100, stdin);
while (strcmp( userInput, "0\n") != 0) {
fputs( userInput, cfPtr);
fgets(userInput, 100, stdin);
} // end while
fclose( cfPtr );
//system("pause");
} // end main