如何计算C中矩阵行中的元素数量

使用整数数组,Id喜欢首先向用户询问他想要在数组中的行数和列数(让我们称之为x和y)(我知道如何执行此步骤)。 重要的是,当用户输入将存储在矩阵中的值时,将从一行输入读入一行,从第二行输入读入第二行,依此类推。 所以一行输入= 1行。

因此,如果他已经定义了x个列,他应该为第一行输入x个数字,所有这些都在一行上。 如何检查x号码是否确实已输入线路? 如果输入的内容越来越少,我将打印错误消息。 是否有某种命令可以检查1行的大小,以便它可以根据用户定义的x进行检查?

到目前为止我编写的代码涉及简单的步骤,但我对如何实现此检查几乎没有任何想法,以确认用户输入的数量与他最初定义的输入量相同。

非常感谢!

由于您希望一次读取一行,因此您应该使用完全相同的fgets 。 然后,您可以使用strtok通过空格/制表符分隔行,并尝试将每个值转换为int。 如果在填充行之前用完了数字,或者在填充行后仍有更多数字,那么您可以提醒用户。

这是一个简单的例子:

 void read_array(int **array, int rows, int cols) { char line[100]; int i,count; char *p; for (i=0;i 

这是另一个解决方案,但另一个答案比我的更好,以满足您的特定要求。

 #include  #include  int main(void) { int number_of_rows; int number_of_columns; printf("Enter the number of rows: "); scanf("%d", &number_of_rows); printf("Ok, enter the number of columns: "); scanf("%d", &number_of_columns); int matrix[number_of_rows][number_of_columns]; int i; int j; for(i = 0; i < number_of_rows; ++i) { printf("This is %d row.\n", i+1); for(j = 0; j < number_of_columns; ++j) { scanf("%d", &matrix[i][j]); } } /* Print's the 2D array. */ for(i = 0; i < number_of_rows; ++i) { printf("\n"); for(j = 0; j < number_of_columns; ++j) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; } 

这样做是要求用户提供用户想要矩阵(2D数组)的行数和列数,然后根据这些数字声明一个二维数组。 然后它循环遍历每一行,在循环遍历每列之前向控制台打印行号。 在初始化2Darrays之后,它以绘制矩阵的方式打印2Darrays。 我希望这有帮助。