循环中的C scanf在没有输入的情况下自动继续

我正在尝试在数组中输入,我希望输入如下。

5 (Number of the second dimensions in the array) 2 (Number of the first dimensions in the array) 

所以我们在这个例子中得到了一个数组deeln [2] [5]。 我尝试使用以下代码获取它:

 #include  #include  #include  bool isinarray(int val, int *arr, int size){ int countimp; for (countimp=0; countimp < size; countimp++) { if (arr[countimp] == val) return true; } return false; } int main(void){ int k, d, ci, cj, ck, ta; //get input scanf("%i", &k); scanf("%i", &d); int deeln[d][k], temp[k]; for(ci = 0; ci < d; ci++){ printf("d= %i, ci= %i \n", d, ci); scanf("%s", temp); for(cj = 0; cj < k; cj++){ deeln[ci][cj] = temp[cj*2]-'0'; } } //loop while. } 

但是我遇到了一个问题,每当我尝试输入时,程序在第二次或第三次循环第三次扫描时自动运行而不会得到任何输入。 那么我就无法输入任何东西了。

该怎么办? 它与指针有关或我使用scanf错了吗?

更新:

如果我在printf之后输入printf("cj is nu %i \n", cj); 然后输出也是在循环以自己的方式进行之后。 而不是在我应该提供更多输入之前,使用第三个scanf。

我的问题的解决方案非常简单。 在考虑了我的输入后我发现了它。 问题是在输入中,如上所述,有空格。 不知何故,scanf无法处理空格,除非您使用其他语法。 但我的解决方案是只使用fgets而不是scanf来获取输入。 所以新的和工作的代码如下:

 #include  #include  #include  bool isinarray(int val, int *arr, int size){ int countimp = 0; for (countimp=0; countimp < size; countimp++) { if (arr[countimp] == val) return true; } return false; } int main(void){ int t, k = 0, d = 0, ci = 0, cj = 0, ta = 0; //get input scanf("%i", &k); scanf("%i", &d); char temp[20]; int deeln[d][k]; memset(deeln, 0 , sizeof(deeln)); memset(temp, 0 , sizeof(temp)); for(ci = 0; ci < d; ci++){ fgets(temp, 20, stdin); for(cj = 0; cj < k; cj++){ ta = cj*2; deeln[ci][cj] = temp[ta]-'0'; } } //loop while. return 1; } 

感谢帮助任何人,即使我们都没有来到这里。 但我希望它会帮助别人!

两个地方看:

1)

 cj = 0;//initialize cj before using here scanf("%i", &temp[cj]);//temp is both an array, and an int. Fix your format specifier, //and use an index operator - temp[?] (not sure I am using the right index) 

2)

  deeln[ci][cj] = temp[cj*2]-'0'; //fix your logic here (array index will be exceeded) 

工作代码的一个例子……

 int main(void){ int k, d, ci, cj, ck, ta; //get input scanf("%i", &k); scanf("%i", &d); int deeln[d][k], temp[k]; for(ci = 0; ci < d; ci++){ printf("d= %i, ci= %i \n", d, ci); for(cj = 0; cj < k; cj++){ if(scanf("%i", &temp[cj]) != EOF) { deeln[ci][cj] = temp[cj]-'0'; } else deeln[ci][cj] = -1; } } getchar(); //loop while. } 

你可以使用temp [cj]的索引来使它成为你真正想要的东西,但是我假设你打算从stdin中读取,然后用每个scanf为该值填充deeln [] []。

如果你想解析一个包含空格和digets的字符串,“1 3 8 5 3”,你可以使用strtok()但是你的代码不是读取字符串,而是读取整数。

这不是完美的,你将不得不做一些调试,但将说明strtok() 。 选择索引后,您必须在每个数字之间输入空格:即:

 3 3 4 6 8 2 4 7 1 2 8 int main(void){ int k, d, ci, cj, ck, ta; //get input scanf("%i", &k); scanf("%i", &d); char inStr[d][k*5]; //space for up to k 3 digit numbers with 1 space each char *buf=0; int deeln[d][k], temp[k]; for(ci = 0; ci < d; ci++){ printf("d= %i, ci= %i \n", d, ci); if(scanf("%s ", inStr[ci]) != EOF) { buf = strtok(inStr[ci], " "); cj = 0; while(buf && (cj < k)) { deeln[ci][cj] = atoi(buf); cj++; } } } //getchar();waits for user input, pauses execution }