【问题标题】:How to check if input from stdin is null or newline如何检查来自标准输入的输入是否为空或换行符
【发布时间】: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;
}

程序预计会这样做

  1. 从命令行接受两个参数,即两个文件的名称
  2. 创建两个带有指针secret 和public 的文件。
  3. 从标准输入读取输入
  4. 在while循环中
    1. 如果输入为空(null 或换行符),则退出循环。
    2. 如果输入包含短语“secret”,则将该行放入机密文件中。
    3. 否则将其放入公共文件中。

问题是检查输入是否为空的代码部分不起作用。该程序不会在空输入(即换行符)上退出。什么是正确的代码?

顺便说一句,我读了How to check if stdin is empty in C,但我什么都不懂。

【问题讨论】:

  • 查看 strcmp 的文档...
  • 我的scanf 无论如何都不接受空行。即使有,它也不会包含newline。我建议if (stricmp(message,"q"))

标签: c string stdin


【解决方案1】:

您可以使用fgets 而不是scanf 来读取字符串。 fgets 不仅可以防止缓冲区溢出,还可以为您提供前导 \n 字符来测试空行。

while( fgets(message, sizeof message, stdin))
...    
  if( message[0] == '\n' ) break; /* Step 4.1 */
  str[ strlen(str) - 1 ] = '\0';  /* remove the newline before sending to the file */

Working example

【讨论】:

    【解决方案2】:

    一个空行,只输入,应该结束这个循环

    while(scanf("%99[^\n]%*c",message)==1)
    {
        if(strstr(message,"secret"))
            fprintf(secret,"%s\n",message);
        else
            fprintf(public,"%s\n",message);
    }
    

    【讨论】:

    • 这个答案太棒了。没想到这样。
    • %*c 到底是做什么的?` 我猜它的意思是“任意数量的字符,但至少为 1”。我说的对吗?
    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多