我编写了一个程序来将数字读取到整数数组 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;
}
最佳答案
我能想到的问题:
数组索引的增量需要更新。
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++;; }
如果您的输入流包含
e
,则语句scanf("%d",&a[i]);
不会向
a[i]
读取任何内容。您可以通过以下方式解决该问题:
- 将输入读取为字符串。
- 检查字符串是否为
e
。如果是这样,请跳出循环。 - 如果没有,请尝试从字符串中获取数字。
这是更新版本:
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/