【发布时间】:2019-04-12 01:49:15
【问题描述】:
我正在尝试制作一个程序,它将用户输入的数据存储在一个由用户提供名称的文本文件中。当用户进入退出时程序将终止。 string.h 的 strcmp 函数用于字符串比较,fgets() 用于从标准输入读取数据。
这是我的代码。
#include<stdio.h>
#include<string.h>
void main()
{
char file[60]; // will store file name
printf("Enter file name: ");
fgets(file, 59, stdin);
FILE *fp = fopen(file, "a+"); // open file in append mode
if(fp == NULL){
printf("File not found !");
return;
}
char data[100];
printf("Enter some data to add to file(exit to terminate): ");
fgets(data, 99, stdin);
int flag = strcmp(data, "exit");
while(flag != 0){
fputs(data, fp);
fgets(data, 59, stdin);
flag = strcmp(data, "exit");
printf("%d\n", flag); // for checking whether string are correctly comapred or not
}
printf("Bye");
}
即使我进入退出程序也不会终止。我还尝试在用户输入的字符串末尾连接“\n”,但这也无济于事。虽然,gets() 函数工作正常,但我知道它不是首选使用,我转移到 fgets() 但它对我不起作用。
【问题讨论】:
-
您传递给
fgets的大小是带有 空终止符的。并始终检查它返回的内容。 -
I have also tried concatenating "\n" at the end of string input by user..也许你需要剥离它。 :) -
@SouravGhosh 还是将其添加到常量字符串文字中?
-
@Someprogrammerdude 很有可能...但不是很优雅...
-
注意:
char file[60]; fgets(file, 59, stdin)不需要负1,最好使用fgets(file, sizeof file, stdin)。
标签: c