【发布时间】:2015-08-10 14:09:50
【问题描述】:
我在学c,写过这段代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
char message[100];
FILE *secret=fopen(argv[1],"w");
FILE *public=fopen(argv[2],"w");
while(scanf("%99s\n",message)==1)
{
if (strcmp(message,"\n")) //this does not work as expected
break;
if(strstr(message,"secret"))
fprintf(secret,"%s\n",message);
else
fprintf(public,"%s\n",message);
}
return 0;
}
程序预计会这样做
- 从命令行接受两个参数,即两个文件的名称
- 创建两个带有指针secret 和public 的文件。
- 从标准输入读取输入
- 在while循环中
- 如果输入为空(null 或换行符),则退出循环。
- 如果输入包含短语“secret”,则将该行放入机密文件中。
- 否则将其放入公共文件中。
问题是检查输入是否为空的代码部分不起作用。该程序不会在空输入(即换行符)上退出。什么是正确的代码?
顺便说一句,我读了How to check if stdin is empty in C,但我什么都不懂。
【问题讨论】:
-
查看 strcmp 的文档...
-
我的
scanf无论如何都不接受空行。即使有,它也不会包含newline。我建议if (stricmp(message,"q"))