这是我的代码的简单版本,当我运行它时仍然无效。当我将i
初始化为for
循环的计数器时,由于某种原因它会跳过0
,这在我之前从未发生过,我不知道为什么。
#include <stdio.h>
#include <string.h>
int main() {
int x, i;
scanf("%d", &x);
char array[x][10];
for (i = 0; i < x; i++) {
printf("%d\n", i);
gets(array[i]);
}
return 0;
}
编辑:我为x
输入5,因此我的字符数组大小为5行,10列。对于i
,它应该从0开始,所以我先输入array[0]
但跳到1,所以我用array[1]
开始输入,这意味着我的第一行没有输入。
答案 0 :(得分:1)
scanf()
会在输入流中留下一些字符,这些字符会在第一次调用gets()
时被拾取,导致第一个gets()
立即完成,程序将继续并提示输入array[1]
的输入,因此&#34;跳过&#34;超过0
。
答案 1 :(得分:0)
scanf()
仅使用构成转换号码的字符。任何剩余的输入,尤其是您在5
之后输入的换行符都会保留在输入流中。
for
循环确实从0
开始,0
必须由您的程序输出,但gets()
读取待处理的输入并包括换行符,因此下一次迭代立即出现:输出1
,程序只等待输入。
请注意,您不能使用过时的函数gets()
,因为它无法确定要存储到目标数组的最大字符数,因此无法避免无效输入上的未定义行为。请改用fgets()
或getchar()
。
以下是修复程序的方法:
#include <stdio.h>
#include <string.h>
int main() {
int x, i, j, c;
if (scanf("%d", &x) != 1)
return 1;
while ((c = getchar()) != EOF && c != '\n')
continue;
char array[x][10];
for (i = 0; i < x; i++) {
printf("%d\n", i);
for (j = 0; (c = getchar()) != EOF && c != '\n';) {
if (j < 9)
array[i][j++] = c;
}
array[i][j] = '\0';
}
return 0;
}