我正在编写一个 C 程序,需要接受最多 100 个字符的用户输入,但允许用户输入少于该限制的字符。我试图用 while 循环来实现这个想法,该循环继续接受 char 输入,直到用户按下 Enter 键(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++;
}
从命令行启动,如果我输入几个字符然后按 Enter 键,提示符只会转到新行并继续接受输入。我认为问题在于我不了解 scanf 如何接收输入,但我不确定如何更改它。当用户按下 Enter 键时,我该怎么做才能使循环中断?
最佳答案
因为您读入 &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'
,这不是您想要的(大多数可能)。
关于C:使用scanf接受预定义的输入长度char[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805180/