在 for 方法中扫描一个字符不能像预期的那样工作
Scanning a char in for method doesn't work like expected
该程序的目标是根据用户将它们放在一起的方式扫描 X、1、2 的序列,然后显示他放入了多少 X。
出于某种原因,我在 8 X/1/2 之后输入(按 ENTER 8 次,因为我一个一个输入)
无论我如何输入数字,它都会显示数字 15。
我的问题是,当为 i=1; i<=TOTOSIZE; i++
设置 for 时,为什么它会在 8 次 ENTER 后停止
TOTOSIZE = 15
为什么它一直显示数字 15 而不是它应该做的事情。
#include <stdio.h>
#define TOTOSIZE 15
int main()
{
int d = 0, i;
char score;
for (i = 1; i <= TOTOSIZE; i++)
{
scanf_s("%c", &score);
if (score == 'X');
{
d++;
}
_flushall();
}
printf("%d", d);
return 0;
}
我可能没有正确理解您的意思,但据我了解,您输入了 15 个不同的字符,每个字符是 1、2 或 X,并计算输入了多少个 X。如果这是正确的,您的问题似乎是 if 语句后的分号。此代码可以工作 -
#include <stdio.h>
#define TOTOSIZE 15
int main()
{
int d = 0, i;
char score;
for (i = 1; i <= TOTOSIZE; i++)
{
scanf_s("%c", &score);
if (score == 'X')
{
d++;
}
_flushall();
}
printf("%d", d);
return 0;
}
您的代码的以下部分中有两项可能会导致跳过问题。 (另一个答案也解决了这个问题。)
for (i = 1; i <= TOTOSIZE; i++)
{
//scanf_s("%c", &score);//using scanf to read char like this may skip due to newlines
scanf_s(" %c", &score);//leading space in format specifier will consume space, including newline.
// ^
if (score == 'X');
{ // ^ should not be there. It nullifies the false result of test
d++;
}
_flushall();
}
leading space reference
该程序的目标是根据用户将它们放在一起的方式扫描 X、1、2 的序列,然后显示他放入了多少 X。
出于某种原因,我在 8 X/1/2 之后输入(按 ENTER 8 次,因为我一个一个输入) 无论我如何输入数字,它都会显示数字 15。
我的问题是,当为 i=1; i<=TOTOSIZE; i++
设置 for 时,为什么它会在 8 次 ENTER 后停止
TOTOSIZE = 15
为什么它一直显示数字 15 而不是它应该做的事情。
#include <stdio.h>
#define TOTOSIZE 15
int main()
{
int d = 0, i;
char score;
for (i = 1; i <= TOTOSIZE; i++)
{
scanf_s("%c", &score);
if (score == 'X');
{
d++;
}
_flushall();
}
printf("%d", d);
return 0;
}
我可能没有正确理解您的意思,但据我了解,您输入了 15 个不同的字符,每个字符是 1、2 或 X,并计算输入了多少个 X。如果这是正确的,您的问题似乎是 if 语句后的分号。此代码可以工作 -
#include <stdio.h>
#define TOTOSIZE 15
int main()
{
int d = 0, i;
char score;
for (i = 1; i <= TOTOSIZE; i++)
{
scanf_s("%c", &score);
if (score == 'X')
{
d++;
}
_flushall();
}
printf("%d", d);
return 0;
}
您的代码的以下部分中有两项可能会导致跳过问题。 (另一个答案也解决了这个问题。)
for (i = 1; i <= TOTOSIZE; i++)
{
//scanf_s("%c", &score);//using scanf to read char like this may skip due to newlines
scanf_s(" %c", &score);//leading space in format specifier will consume space, including newline.
// ^
if (score == 'X');
{ // ^ should not be there. It nullifies the false result of test
d++;
}
_flushall();
}
leading space reference