繁体   English   中英

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

[英]C: Using scanf to accept a predefined input length char[]

我正在编写一个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' ,这不是您想要的(很可能)。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM