【问题标题】:Issues while inputting strings in C在 C 中输入字符串时的问题
【发布时间】:2015-07-10 17:48:44
【问题描述】:

我正在尝试编写一个将n 作为整数输入然后输入n 字符串的C 程序。当我运行程序时,它比n 少一个输入的问题。如果我输入1 作为第一个输入,程序就会终止。这是代码:

int n;
scanf("%d", &n);
char str[101];

while (n--) {
    fgets(str, 101, stdin);
    // other stuff...
}

我在这里做错了什么?

【问题讨论】:

    标签: c string input scanf fgets


    【解决方案1】:

    如果您将scanf() 用于数字字符串输入,您的程序将运行。

    #include <stdio.h>
    
    int main()
    {
        int n;
        char str[101];
        scanf("%d", &n);
        while (n--)
        {
            scanf("%s", str);
        }
        return 0;
    }
    

    但可以说对所有输入都使用fgets() 更好。

    #include <stdio.h>
    
    int main()
    {
        int n;
        char str[101];
        fgets(str, 100, stdin);
        sscanf(str, "%d", &n);
        while (n--)
        {
            fgets(str, 100, stdin);
        }
        return 0;
    }
    

    我几乎不需要提醒你,因为你首先使用了fgets(),你会知道它在输入字符串的末尾保留了newline

    【讨论】:

    • 注意:最好使用fgets(str, sizeof str, stdin); 1) 应该是 101 而不是 100 和 2) 避免幻数。 +1 表示“最好将 fgets() 用于所有输入。”
    【解决方案2】:

    请记住,按下回车键也会将字符发送到流中。您的程序无法解决此问题。使用格式scanf(%d%*c) 丢弃第二个字符。

    int main(void) {
    
        int n;
    
        scanf("%d%*c", &n);
    
        char str[101];
    
        while (n--)
        {
            fgets(str, 101, stdin);
    
            // other stuff.....
        }
    
    }
    

    【讨论】:

      【解决方案3】:
      int n;
      scanf("%d", &n);
      char str[101];
      
      while (n--) 
      {
      fgets(str, 101, stdin);
      // other stuff...
      }
      

      在此,当您输入n 并从键盘按ENTER 时,'\n 存储在stdin 中,因此fgets 遇到newline character 如果返回。

      因此在scanf之后使用这个-

       char c ;
      while((c=getchar())!=NULL && c!='\n');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-05
        • 2018-12-09
        相关资源
        最近更新 更多