【发布时间】:2017-10-27 18:10:06
【问题描述】:
我正在尝试将一些 ints 保存到从用户输入读取的数组中。我不知道每行上ints 的数量,只知道行数,这也是该行上ints 的最大数量。例如,如果这是 5,那么用户应该输入 5 行 ints 并且每行最多包含 5 个元素。值将是正数。我做错了什么?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n;
scanf("%d",&n);
int array_row[n];
int i=0;
int noEnter=n;
//My idea is when in getchar() there is a enter it means that the user wants to go to the next line so decrement noEnter with 1 and also store a value -1 which tells me that that was the end of the line
while(noEnter!=0){
int c;
if(scanf("%d",&c)==1){
array_row[i]=c;
i++;
continue;
}
char d=getchar();
if(d=='\n'){
array_row[i]=-1;
i++;
noEnter--;
continue;
}
}
for(int i=0;i<n*n;i++){
printf("%d ",array_row[i]);
}
return 0;
}
输入示例:
5
4
4 35 65
4 32
2 222 4 5 6
4
输出:
4 -1 4 35 65 -1 4 32 -1 2 222 4 5 6 -1 4 -1
【问题讨论】: