[英]Several statements while loop
I'm trying to put another statement to end the while-loop with logical AND:我正在尝试使用另一个语句以逻辑 AND 结束 while 循环:
while ( (character != '\n') && ( i < 10 ) )
...the extra +10:th letters does not get stored in the array. ...额外的 +10:th 字母不会存储在数组中。 But I can still type in input until pressing ENTER / '\n'.
但我仍然可以输入输入,直到按 ENTER / '\n'。
What am I doing wrong?我究竟做错了什么? What happens with the 'extra input'?
“额外输入”会发生什么?
This is the code:这是代码:
char character;
char buffer[81];
int i = 0;
do
{
character = getchar();
buffer[i] = character;
++i;
} while ( (character != '\n') && (i < 10) );
buffer[i-1] = '\0';
The function getchar
does not read directly from the keyboard. function
getchar
不直接从键盘读取。 It reads from stdin
.它从
stdin
读取。 And in most cases what you have written on the keyboard will not end up in stdin
until you press enter.在大多数情况下,您在键盘上写的内容在您按下回车之前不会以
stdin
结尾。 This behavior is outside your control and is determined by the terminal you are using.此行为不在您的控制范围内,由您使用的终端决定。
So your code basically works, except that you should change buffer[i-1]
to buffer[i]
.所以你的代码基本上可以工作,除了你应该将
buffer[i-1]
更改为buffer[i]
。 If you want to detect keypresses directly, then you will need different methods.如果您想直接检测按键,那么您将需要不同的方法。 There are no good functions in the standard library to do this, but here is an answer that gives you two options.
标准库中没有很好的函数可以做到这一点,但这里有一个答案,它为您提供了两种选择。 https://stackoverflow.com/a/20349652/6699433
https://stackoverflow.com/a/20349652/6699433
When the do-while loop stops, i
becomes 10 in your case.当 do-while 循环停止时,
i
在您的情况下变为 10。 Let's say your input was 0123456789
.假设您的输入是
0123456789
。 The input does not contain \n
so buffer[9]
becomes '9'
.输入不包含
\n
所以buffer[9]
变成'9'
。 Now, after that you are assigning buffer[i - 1]
to \0
and buffer[9]
becomes \0
.现在,之后您将
buffer[i - 1]
分配给\0
并且buffer[9]
变为\0
。
You want buffer[i] = '\0'
.你想要
buffer[i] = '\0'
。 Also, do not forget to check that i
does not cross the buffer size.另外,不要忘记检查
i
是否跨越缓冲区大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.