2

所以我有这段代码,它应该从用户那里获取坐标:

#include <stdio.h>
#include <time.h>

int main() {
int number;
char letter;
int points = 3;
    while(points < 8){
        printf("give me first coordinate (letter)");
        scanf("%c",&letter);
        printf("give me second coordinate (number)");
        scanf("%d",&number);
    }
}

据我所知,这应该继续从用户那里获取坐标,但它只需要一次,然后以一种非常奇怪的方式粉碎,就像它无缘无故地跳过 scanf 一样。这是我的输出:

give me first coordinate (letter)a
give me second coordinate (number)1
give me first coordinate (letter)give me second coordinate (number)12
give me first coordinate (letter)give me second coordinate (number)df
give me first coordinate (letter)give me second coordinate (number)give me first coordinate (letter)give me second coordinate (number)sss

我真的很困惑,因为这是简单的代码,我不知道是什么原因造成的。有人吗?(如果有什么不同,我的系统是山狮)

4

3 回答 3

6

One possible solution is to add a space to skip whitespace:

scanf(" %c",&letter);
       ^

As user "undefined behavior" properly pointed out, you should also check the return value. In this case you expect the return value to be equal to the number of items you are reading, if the return value <0 then you can't read from stdin anymore and a return value less than the number of items you are reading in indicates you have a conversion error.

于 2013-05-08T18:41:14.643 回答
3
scanf(" %c",&ch);

这样做的原因是第一个空格会刷新标准输入,然后让用户输入字符。

如果你放/n/t之前,这也有效%c

于 2014-06-26T19:10:48.610 回答
-1

我个人不喜欢使用scanf。此函数使输入流处于不像看起来那样定义良好的状态。我更喜欢 fgets 结合 sscanf ...

于 2013-05-08T18:40:42.167 回答