我需要这个简单代码的帮助:
#include <stdlib.h>
#include <stdio.h>
int main() {
system("clear");
while (1) {
printf("Enter your name(MAX 24 chars) : ");
char name[25];
int x = 0;
do {
name[x] = getchar();
x++;
} while (x != 24 && !(name[x - 1] == 'n'));
name[x - 1] = ' ';
printf("Well it looks like your name is : %sn", name);
}
}
它有效,但它做了一件奇怪的事情:
Enter your name(MAX 24 chars) : 123456789012345678901234567890
Well it looks like your name is : 12345678901234567890123
Well it looks like your name is : 567890
Enter your name(MAX 24 chars) :
当我用太多字符填充getchar()
时,它会执行两次printf
行,并将其余部分打印在下一行中。
我的问题是:为什么会这样?
编辑:答案很好,但有人在评论中指出输出顺序不对。为什么循环跳过 printf(( ?
(我也不是本地人,所以对不起英语不好(
当我用太多字符过度填充 getchar(( 时,它会对 printf 行执行两次,并将其余部分打印在下一行中。 我的问题是:为什么会这样?
当您只读取部分输入时,其余字符仍存在于输入流中。因此,当外部循环继续时,getchar()
将剩余的字符读入name
。
使用fgets()
通常是更好的选择,但"额外"输入仍然会遇到同样的问题。
您可以使用一个简单的循环来使用输入中可能存在的任何额外字符(在内部 while 循环之后(:
int ch;
while((ch=getchar()) != EOF && ch != 'n');
代码示例中出现双重打印的原因已经得到解答。 若要改进处理用户输入的方式,请考虑结合使用 fgets 和 sscanf 来读取用户输入:
char name[25];
char c[25];
printf("Enter your name(MAX 24 chars) : ");
fgets(c, sizeof(c), stdin);//reads string input from stdin. into c,
//including newline char.
sscanf(c, "%s", name);//string 'c' is evaluated and parsed into 'name'.
//The %s format specifier, when used in sscanf,
//consumes white space, such as n.
您正在按 int x=0 重置数组,因此它正在重新打印,这是一个无限循环。解释如下:
while(1){ // enter infinite loop 2nd time
printf("Enter your name(MAX 24 chars) : ");
char name[25]; //declare new array 2nd declaration
int x=0; //reset of loop counter 2nd reset
do{
name[x] = getchar(); // start reading 2nd time read from the stream
x++;
}while(x!=24 && !(name[x-1] == 'n')); // stop reading but data is
//in stream
name[x-1] = ' '; // end of string marker
printf("Well it looks like your name is : %sn",name); // print and
//enter loop again
}
时,程序最多只扫描 24 个字符,然后打印名称并开始下一个循环。 由于存在上一个循环中未扫描的字符,因此它们将在流循环中扫描。 由于存在现有字符而要求输入。
如果调试程序,则可以清楚地看到正在发生的事情。