问题描述
我试图做一个简单的C程序一类的要求之一就是我需要使用 scanf函数
/ 的printf
所有输入和输出。我的问题是为什么是我 scanf函数
I am trying to make a simple C program for a class and one of the requirements is that I'm required to use scanf
/printf
for all input and output. My question is why is it that my scanf
after the for loop in the main gets skipped and the program just terminates.
下面是我的code
#include <stdio.h>
void main() {
int userValue;
int x;
char c;
printf("Enter a number : ");
scanf("%d", &userValue);
printf("The odd prime values are:\n");
for (x = 3; x <= userValue; x = x + 2) {
int a;
a = isPrime(x);
if (a = 1) {
printf("%d is an odd prime\n", x);
}
}
printf("hit anything to terminate...");
scanf("%c", &c);
}
int isPrime(int number) {
int i;
for (i = 2; i < number; i++) {
if (number % i == 0 && i != number)
return 0;
}
return 1;
}
我能够加入另一个相同的修理它 scanf函数
后的第一个,但我会preFER只使用一个。
I was able to "fix" it by adding another identical scanf
after the first one, but I would prefer to just use the one.
推荐答案
新的行字符present在标准输入
的previous后 INT
被输入不会被最后调用消耗 scanf()的
。因此调用 scanf()的
的为
循环消耗换行字符,并继续无需用户后,输入任何东西。
The new-line character present in stdin
after the previous int
was entered will not have been consumed by the last call to scanf()
. So the call to scanf()
after the for
loop consumes the new-line character and continues without the user having to enter anything.
要纠正,而无需添加其他 scanf()的
调用,您可以使用格式说明%C
中在 scanf()的
在为
循环。这将使 scanf()的
跳过任何前导空白字符(包括新行)。注意这意味着用户必须输入大于新行以结束该程序以外的东西。
To correct without having to add another scanf()
call you could use format specifier " %c"
in the scanf()
after the for
loop. This will make scanf()
skip any leading whitespace characters (including new-line). Note it means the user will have to enter something other than a new-line to end the program.
此外:
-
检查的结果
scanf()的
,以确保它实际上分配一个值传递的变量:
check the result of
scanf()
to ensure it actually assigns a value to the variables passed in:
/* scanf() returns number of assigments made. */
if (scanf("%d", &userValue) == 1)
这是一个任务(而且将永远是真实的):
this is an assignment (and will always be true):
if (a = 1){ /* Use == for equality check.
Note 'a' could be removed entirely and
replace with: if (isPrime(x)) */
这篇关于scanf函数获取跳过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!