在while循环中使用scanf函数 [英] Using the scanf function in while loop
问题描述
我正在尝试为编程作业格式化以空格分隔的用户输入.
I am attempting to format a space-delimited user input for a programming assignment.
本质上,输入由任意数量的表达式组成
Essentially, the input consists of an arbitrary number of expressions
L integer integer integer
和 C integer integer integer
.
例如:L 1 1 5 7 C 4 5 3
.
到目前为止,我已经设法根据初始字符提取整数,并且可以使用 scanf 函数遍历字符串:
So far, I've managed to extract the integers depending on the initial character, and can iterate through the string using the scanf function:
char a;
while(scanf("%c", &a) == 1){
if(a == 'C'){
int inputX, inputY, inputR;
scanf("%d %d %d", &inputX, &inputY, &inputR);
printf("%d %d %d
", inputX, inputY, inputR);
}
else if(a == 'L'){
int x1, y1, x2, y2;
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
printf("%d %d %d %d
", x1, y1, x2, y2);
}
}
不幸的是,虽然这会输出所需的整数,但循环(和用户输入提示)并没有终止.
Unfortunately, although this outputs the desired integers, the loop (and user input prompt) doesn't terminate.
有人能告诉我为什么会这样吗?
Could someone please enlighten me as to why this is happening?
推荐答案
这是因为
总是在那里使 scanf("%c", &a) ==1
总是正确的.
改变你的
This is because
is always there to make scanf("%c", &a) == 1
always true.
Change your
while(scanf("%c", &a) == 1)
到
while(scanf(" %c", &a) == 1)
// ^space before format specifier.
%c
之前的空格会吃掉 scanf
留下的这个
(按 Enter).
A space before %c
will eat up this
left behind by scanf
(on pressing Enter).
这篇关于在while循环中使用scanf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!