我正在为类(class)编写一个程序,要求用户输入二维数组的大小,然后让用户输入数组的值。这是我到目前为止的代码:
#include <stdio.h>
int main(void)
{
// Setup
int N, M;
int row = 0, col = 0;
printf("\n");
printf("This program counts occurences of digits 0 through 9 in an NxM array.\n");
printf("Enter the size of the array (Row Column): ");
scanf(" %d %d", &N, &M);
int array[N][M];
// Array Input
for (row = 0; row < N; row++)
{
printf("Enter row %d: ", row);
for (col = 0; col < M; col++);
{
scanf(" %d", &array[row][col]);
}
}
printf("\n");
return 0;
}
当编译程序并输入信息时,我遇到的问题是跳过第二个和所有后续的 scanf() 语句,或者在输入第一行后跳过整个第二个 for 循环。以下是输入的示例:
This program counts occurences of digits 0 through 9 in an NxM array.
Enter the size of the array (Row Column): 2 6
Enter row 0: 0 1 2 3 4 5
Enter row 1:
然后程序就完全结束了。我真的不知道为什么它被跳过。我尝试更改 scanf() 语句中的空格数量,但无论我更改什么,都会出现相同的问题。我不确定我是否错过了一些我犯过的愚蠢错误,或者是否存在更大的问题。我对编码还很陌生。
最佳答案
你只是有一个杂散的分号。尝试改变
for (col = 0; col < M; col++);
{
至:
for (col = 0; col < M; col++)
{
for
引入了一个控制下一条语句的语句,该语句可以是一个以分号结尾的简单语句、另一个控制语句或使用 {
的复合语句大括号}
。在您的代码中,与 for
关键字位于同一行的分号将被视为无效语句。因此,该代码只会将循环变量增加适当的次数,然后才继续进行下一部分。
确保启用编译器警告。 (gcc 和 clang 都提供了明确的警告,表明此代码可能不会执行您的意思。)
关于c - 为什么在 C 语言的嵌套 for 循环中 scanf() 被跳过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957131/