C scanf()问题 [英] C scanf() problem

查看:15
本文介绍了C scanf()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,无论如何也找不出我在这里做错了什么。第一个scanf运行良好,变量在读入时被打印出来。第二个scanf似乎没有正确读取输入。输入的格式为"char int",即b4 4
当我打印opb x和y输出时,opb="",x=13238272,y=0。 有什么想法吗?.注意,我删掉了问题下面的代码

int main(void)
{

/*initialize variables*/
int width, height;
char op;

/*grid input*/
scanf("%c %d %d", &op, &width, &height);

/*check conditions*/
if (op != 'g' || width>100 || height>100 || width*height<10 || width<1 || height<1) {
    printf("grid-error
");
    return 0;
}

/*initialize grid elements*/
int grid[width][height];
char printGrid[width][height];

/*create grid elements*/
int i, j;
for (i=0; i<height; i++) {
    for (j=0; j<width; j++) {
        grid[j][i] = 0;
        printGrid[j][i] = '*';
    }
}

/*print successful creation*/
printf("%c %d %d 
", op, width, height);

int k;
for (k = 0; k<10; k++) {
    /*initialize variables*/
    int x, y;
    char opb;

    /*mine input*/
    scanf("%c %d %d", &opb, &x, &y);

    /*check conditions*/
    if (opb != 'b' || x<0 || y<0 || x>(width-1) || y>(height-1) || grid[x][y] == 9) {
        printf("mine-error
");
        return 0;
    }

推荐答案

我怀疑问题在于您没有在输入中处理换行符。结果是opb实际上是换行符(不是空格,尽管它看起来像一个空格),并且xy根本不会被读取(即它们保留初始化时使用的值)。

要解决此问题,请尝试将换行符添加到您的两个scanfs中。即:

scanf("%c %d %d
", &op, &width, &height);

及更高版本

scanf("%c %d %d
", &opb, &x, &y);

这篇关于C scanf()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆