【问题标题】:C: Using scanf to accept a predefined input length char[]C: 使用 scanf 接受预定义的输入长度 char[]
【发布时间】:2014-03-15 08:07:06
【问题描述】:

我正在编写一个 C 程序,它需要接受最多 100 个字符的用户输入,但允许用户输入少于该限制。我试图用一个while循环来实现这个想法,该循环继续接受字符输入,直到用户按下回车键(ascii值为13),此时循环应该中断。这是我写的:

char userText[100]; //pointer to the first char of the 100
int count = 0; //used to make sure the user doens't input more than 100 characters


while(count<100 && userText[count]!=13){ //13 is the ascii value of the return key
    scanf("%c", &userText[count]);
    count++;
}

从命令行启动,如果我输入几个字符然后按回车,提示符只是换行并继续接受输入。我认为问题在于我不了解 scanf 如何接收输入,但我不确定如何更改它。当用户按下回车时,我该怎么做才能使循环中断?

【问题讨论】:

    标签: c scanf


    【解决方案1】:

    因为你读入&amp;userText[count],然后执行count++,所以你循环条件userText[count]!=13使用count的新值。您可以使用以下方法修复它:

    scanf("%c", &userText[count]);
    while(count<100 && userText[count]!='\n'){
        count++;
        scanf("%c", &userText[count]);
    }
    

    正如 Juri Robl 和 BLUEPIXY 指出的那样,'\n' 是 10。13 是 '\r',这不是你想要的(很可能)。

    【讨论】:

      【解决方案2】:

      您可能应该检查 \n (=10) 而不是 13。此外,您检查错误的 count,它已经是一到高了。

      int check;
      do {
        check = scanf("%c", &userText[count]);
        count++;
      } while(count<100 && userText[count-1]!='\n' && check == 1);
      userText[count] = 0; // So it's a terminated string
      

      另一方面,您可以使用scanf("%99s", userText);,它最多允许输入 99 个字符(最后一个用于 0)。

      检查check == 1 查找读取错误,例如EOF

      【讨论】:

        【解决方案3】:
        while(count<100 && scanf("%c", &userText[count]) == 1 && userText[count]!='\n'){
            count++;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-09
          • 2019-07-10
          • 2016-02-29
          • 1970-01-01
          • 1970-01-01
          • 2015-05-30
          • 2015-04-02
          • 2012-01-20
          相关资源
          最近更新 更多