C:使用scanf接受预定义的输入长度char[]

标签 c scanf

我正在编写一个 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/

相关文章:

c++ - 没有匹配函数调用 sscanf

c - scanf 之后 fgets 不起作用

c - 检查 unsigned long long 的正确输入时出现负数错误

c - 访问超出报告容量的 block 设备数据

c++ - C/C++ NaN 解析

c++ - 释放后分配给指针

c - 如何使用scanf检查用户是否输入了整数

c++ - 自制超时的最佳实践

c - 为什么我不能通过这个指针 hack 找到元素大小?

PHP重命名文件,以特殊名称开头?