[英]Reading 3 characters in a line until a specific character is typed
I'm trying to use scanf
to read 3 inputs in a line until it encounters a character 'E'
in a newline.我正在尝试使用
scanf
在一行中读取 3 个输入,直到在换行符中遇到字符'E'
。 Why it doesn't stop scanning until I type in an another character after the character 'E'
?为什么它不会停止扫描,直到我在字符
'E'
之后输入另一个字符?
char s[200];
char ch='A';
int ind=0;
while(ch!='E')
{
scanf("%c ",&ch);
s[ind]=ch;
ind=ind+1;
}
printf("%c",s[2]);
It's because you have a trailing space in the scanf
format string.这是因为您在
scanf
格式字符串中有一个尾随空格。
That will lead scanf
to read and ignore all white-space (spaces, tab, newlines) until it reaches a non-space character.这将导致
scanf
读取并忽略所有空格(空格、制表符、换行符),直到它到达非空格字符。
One simple solution is to use leading space in the format string:一种简单的解决方案是在格式字符串中使用前导空格:
scanf(" %c",&ch);
// ^
// Note leading space
I haven't added any error checking, but you should really check what scanf
returns .我没有添加任何错误检查,但您应该真正检查
scanf
返回的内容。 I also recommend you add it as a part of the loop condition itself:我还建议您将其添加为循环条件本身的一部分:
char ch;
while (scanf(" %c", &ch) == 1 && ch != 'E')
{
// Use ch
}
Another possible solution is to use a character-reading function like fgetc
or getc
or getchar
.另一种可能的解决方案是使用像
fgetc
或getc
或getchar
这样的字符读取 function 。 But do note that these return an int
which is important because you also need to remember to check the character returned against EOF
:但请注意,这些返回的
int
很重要,因为您还需要记住检查返回的字符与EOF
:
int ch; // Need to be an int for the EOF check to work
while ((ch = getc(stdin)) != EOF && ch != 'E')
{
if (isspace(ch))
continue; // Don't bother with any kind of space
// Use ch
}
While using getc
as shown above might seem to be more work, it's also more flexible and give you greater control over how to handle different character and character classes.虽然使用如上所示的
getc
似乎工作量更大,但它也更灵活,让您可以更好地控制如何处理不同的字符和字符类。
You can use getc
or fgetc
for better answer.您可以使用
getc
或fgetc
获得更好的答案。 Here I am pasting a working code.在这里,我正在粘贴一个工作代码。
#include <stdio.h>
int main ()
{
char s[200];
char ch = 'A';
int ind = 0;
while (ch != 'E')
{
ch = getc(stdin); //Instead of scanf you can use getc
s[ind] = ch;
ind = ind + 1;
}
printf ("%c", s[2]);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.