读取一行中的 3 个字符,直到键入特定字符
Reading 3 characters in a line until a specific character is typed
我正在尝试使用 scanf
读取一行中的 3 个输入,直到在换行符中遇到字符 '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]);
My result image
这是因为您在 scanf
格式字符串中有一个 尾随 space。
这将导致 scanf
读取并忽略所有白色-space(spaces、制表符、换行符),直到它到达非 space 字符。
一个简单的解决方案是在格式字符串中使用 leading space:
scanf(" %c",&ch);
// ^
// Note leading space
我没有添加任何错误检查,但你真的应该检查什么 scanf
returns。我还建议您将其添加为循环条件本身的一部分:
char ch;
while (scanf(" %c", &ch) == 1 && ch != 'E')
{
// Use ch
}
另一种可能的解决方案是使用像 fgetc
or getc
or getchar
这样的字符读取功能。但请注意这些 return 和 int
这很重要,因为您还需要记住检查字符 returned 与 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
}
虽然如上所示使用 getc
似乎工作量更大,但它也更灵活,让您可以更好地控制如何处理不同的字符和字符 类.
您可以使用 getc
或 fgetc
以获得更好的答案。在这里,我粘贴了一个工作代码。
#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;
}
我正在尝试使用 scanf
读取一行中的 3 个输入,直到在换行符中遇到字符 '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]);
My result image
这是因为您在 scanf
格式字符串中有一个 尾随 space。
这将导致 scanf
读取并忽略所有白色-space(spaces、制表符、换行符),直到它到达非 space 字符。
一个简单的解决方案是在格式字符串中使用 leading space:
scanf(" %c",&ch);
// ^
// Note leading space
我没有添加任何错误检查,但你真的应该检查什么 scanf
returns。我还建议您将其添加为循环条件本身的一部分:
char ch;
while (scanf(" %c", &ch) == 1 && ch != 'E')
{
// Use ch
}
另一种可能的解决方案是使用像 fgetc
or getc
or getchar
这样的字符读取功能。但请注意这些 return 和 int
这很重要,因为您还需要记住检查字符 returned 与 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
}
虽然如上所示使用 getc
似乎工作量更大,但它也更灵活,让您可以更好地控制如何处理不同的字符和字符 类.
您可以使用 getc
或 fgetc
以获得更好的答案。在这里,我粘贴了一个工作代码。
#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;
}