无法弄清楚为什么 getchar() 在 C 中第一次出现时选择换行符

标签 c newline getchar

我正在参加“C”的培训类(class)并遇到了问题。很难解释,所以我会发布代码。这是训练语法,所以不要问我为什么要这样做。当这两个段 block 都在 main() 中运行时,第二个 block 的行为就好像它单独存在于 main() 中一样。我尝试了几个 IDE,认为这可能是一个错误。

/* First Segment Block */
int c;
printf("Type a letter: ");
c = getchar();
printf("You typed '%c'\n",c);

/* OR - outputs the same, to demonstrate putchar */

printf("You typed '");
putchar(c);
printf("'\n\n");

/* Second Segment Block */
int a,b,d;
printf("Type two letters: ");
a = getchar();
b = getchar();
d = getchar();
printf("You typed '");
putchar(a);
printf("' and '");
putchar(b);
printf("' and '");
putchar(d);
printf("'\n");

在第二个分段 block 中,我添加了第三个变量来检验我的理论。当您输入要求的 2 个字母时,第一个 getchar() 会换行,第二个 getchar() 会选择第一个字母。第三个 getchar() 获取第二个字母。如果您注释掉整个第一个段 block ,那么它会正确运行,第一个 getchar() 获取第一个字母,第二个 getchar() 获取第二个字母,按预期显示输出。

这是两者一起运行时的输出。

Type a letter: k
You typed (k)
You typed 'k'

Type two letters: lk
You typed '
' and 'l' and 'k'

RUN SUCCESSFUL (total time: 9s)

当它们单独运行时,输出如下。

第一段输出

Type a letter: k
You typed (k)
You typed 'k'

RUN SUCCESSFUL (total time: 5s)

第二段输出。

Type two letters: rf
You typed 'r' and 'f' and '
'

RUN SUCCESSFUL (total time: 5s)

第三个 getchar() 是一个换行符,这是预期的。

谁能解释为什么当两个段在同一个 main() 中运行时,行为与单独运行时不同?

先谢谢你, Daniel N.(C语言初学者)

最佳答案

在第一个提示符下,您键入类似 aEnter 的内容,因此您的输入流包含字符 'a'、'\n'。第一个 getchar 调用读取 a 并将换行符留在输入流中。

为了响应第二个提示,您键入 bcEnter,因此您的输入流现在包含 '\n' , 'b', 'c', '\n'

您可能会从这里弄清楚发生了什么 - 下一个 getchar 调用从输入流中读取换行符。

有几种方法可以解决这个问题。一种是测试你的输入,如果是换行再试:

do
{
  a = getchar();
} while ( a == '\n' );  // or while( isspace( a )), if you want to reject
                        // any whitespace character.

另一种是不使用getchar;相反,将 scanf%c 转换说明符和格式字符串中的空格一起使用:

scanf( " %c", &c ); // you will need to change the types of your 
...                 // variables from int to char for this.
scanf( " %c", &a );
scanf( " %c", &b );
scanf( " %c", &c );

格式字符串中的前导空格告诉 scanf 忽略任何前导空格,因此您不会选择换行符。

关于无法弄清楚为什么 getchar() 在 C 中第一次出现时选择换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41168213/

相关文章:

c - UNIX 套接字连接被拒绝

c - Q : Reading from pipe to screen

java - 客户端正在从 TCP 套接字中丢失一些线路

java - Java printf 中的 "%n"是怎么回事?

javascript - 如何删除 IE 中文本框中字符串之间的 crlf

c - 管理内存方向数组

c - 尝试在 C 中发送数据包时 TCP 校验和不正确

c - for 循环条件下的 getchar()

c - getchar() 的行为对于该程序是否正确?

c - 为什么我的第二个 printf 没有按预期调用?