gpt4 book ai didi

C scanf() 问题

转载 作者:行者123 更新时间:2023-12-05 01:29:17 26 4
gpt4 key购买 nike

我是 C 语言的新手,我终其一生都无法弄清楚我在这里做错了什么。第一个 scanf 工作正常,变量在读入时打印出来。第二个 scanf 似乎没有正确读取输入。输入格式为“char int int”,即 b 4 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\n");
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 \n", 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\n");
return 0;
}

最佳答案

我怀疑问题是您没有处理输入中的换行符。结果是 opb 实际上是一个换行符(不是空格,虽然它看起来像一个)而 xy 不是完全读取(即它们保留了它们初始化时使用的值)。

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

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

以后

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

关于C scanf() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5401419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com