c - 在 while 循环内使用 scanf 读取数组时出现意外行为

标签 c arrays while-loop scanf

我编写了一个程序来将数字读取到整数数组 a[100] 中。当用户输入字符“e”或数组达到最大大小时,读取就会停止。

但是当代码运行时,我得到了一个意想不到的行为,当用户输入“e”时,数字扫描到数组中会按照我在程序中的预期终止,但 while 循环内的其余语句包括增量变量(i++)和 printf 函数我用来调试代码,直到 while 的条件部分中的第一个条件变为 false。

#include <stdio.h>

int main(){
int a[100];
puts("Enter numbers(enter \"e\" to stop entring)\n");
int i=0;
scanf("%d",&a[i]);
while(i<100&&a[i]!='e'){
     i++;;
     scanf("%d",&a[i]);
     printf("\n -----> %d\n",i);
}
printf("\n\t i ---> %d\t\n",i);
return 0; 
}

最佳答案

我能想到的问题:

  1. 数组索引的增量需要更新。

    while(i<100&&a[i]!='e'){
         // When i 99 before this statement, i becomes 100 after the increment
         i++;;
         // Now you are accessing a[100], which is out of bounds.
        scanf("%d",&a[i]);
        printf("\n -----> %d\n",i);
    }
    

    您需要的是:

    while(i<100&&a[i]!='e'){
        scanf("%d",&a[i]);
        printf("\n -----> %d\n",i);
        i++;;
    }
    
  2. 如果您的输入流包含 e,则语句

    scanf("%d",&a[i]);
    

    不会向 a[i] 读取任何内容。

    您可以通过以下方式解决该问题:

    1. 将输入读取为字符串。
    2. 检查字符串是否为e。如果是这样,请跳出循环。
    3. 如果没有,请尝试从字符串中获取数字。

    这是更新版本:

    char token[100]; // Make it large enough 
    while(i<100) {
        scanf("%s", token);
        if ( token[0] == 'e' ) // Add code to skip white spaces if you 
                               // want to if that's a possibility.
        {
           break;
        }
        sscanf(token, "%d", &a[i]);
        printf("\n -----> %d\n",i);
        i++;;
    }
    

关于c - 在 while 循环内使用 scanf 读取数组时出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27417797/

相关文章:

c - Dos 中断处理程序锁定程序

c - 为什么我的 while(read) 管道循环永远不会结束?

php - 使用 LIMIT 计算 MySQL 记录

java - 如何将数组传递给构造函数并在类中使用它?

python - 如何在Python中创建一个矩形矩阵?

php - DRY - 将一定数量的元素添加到数组末尾,直到它的计数达到特定的 int

java - 不使用 If 或 Break 中断 while 循环

c - 用于查找数字阶乘的递归函数

将 char* 转换为 unsigned char*

c - 为什么 C 不使用变量编译日志,而是使用魔数(Magic Number)编译?