简体   繁体   English

C编程:for循环和中断

[英]C Programming : for loop and break

Can anybody tell me why the loop does not exit whenever I press letter X? 有人可以告诉我为什么每次按字母X时循环都不退出吗? How to make the program not get the value of backspace and enter into the array? 如何使程序不获取退格键的值并输入数组?

#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#define N 2
#define M 4


int main()
{
int i,j,a[N][M];

for(i=0;i<N;i++)
{
    for(j=0;j<M;j++)
    {
        scanf("%c",&a[i][j]);
        if(a[i][j]=='X')
            break;
    }
        if(a[i][j]=='X')
            break;
}
    return 0;
}

Change scanf("%c",&a[i][j]); 更改scanf("%c",&a[i][j]); to scanf(" %c",&a[i][j]); scanf(" %c",&a[i][j]);

This allows for any spaces to be bypassed before scanning the character. 这允许在扫描字符之前绕过任何空格。

There are two problems in your code: 您的代码中有两个问题:

  • The first one is already pointed out by Rishikesh Raje: You need to add a space to the scanf() command in order to eat up the scanned "\\n" characters. Rishikesh Raje已经指出了第一个:您需要在scanf()命令中添加一个空格,以占用扫描的“ \\ n”字符。

  • Then, you scan characters (%c) and try to store them in an int-array. 然后,您扫描字符(%c)并尝试将它们存储在int数组中。 Use 采用

     char a[N][M]; 

    instead. 代替。 My gcc gives a warning at your erroneous code. 我的gcc对您的错误代码发出警告。 Other compilers may silently ignore this. 其他编译器可能会默默地忽略这一点。

    Still, in an little-endian-environment (Like PC's) one could think: a char stored at the address of an int-variable should result in the same value. 不过,在小端环境(如PC)中,人们可能会认为:存储在int变量地址处的char应该产生相同的值。 However, the char-value occupies only one byte, the remaining bytes (3 or more) keep uninitialized. 但是,char值仅占用一个字节,其余字节(3个或更多)保持未初始化状态。 If there were zero-bytes before, than a[i][j] will be 'X', otherwise, it will be some random number. 如果之前有零字节,则a[i][j]将为'X',否则它将为某个随机数。

    This explains the behaviour, I think you observed: The program stopped randomly at some 'X' but not always. 我认为您已经观察到了这种现象:程序在某些“ X”处随机停止,但并非总是停止。

Change the type of array a from int to char 将数组a的类型从int更改为char

int i,j,a[N][M];

change to 改成

int i,j;
char a[N][M];

Usually gcc would warn you too for this: 通常,gcc也会为此警告您:

so.c: In function ‘main’:
so.c:16:9: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int *’ [-Wformat=]
         scanf("%c",&a[i][j]);

Make it an char array instead of an int array 将其设为char数组而不是int数组

char a[N][M];

Instead of, 代替,

int a[N][M];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM