
C语言如何按行输入数组:使用scanf函数逐行读取、使用fgets读取字符串并解析、在循环中逐行输入。逐行读取并解析输入是推荐的方法,因为它允许处理更复杂的输入格式和避免常见的输入错误。下面将详细介绍如何使用不同的方法实现按行输入数组。
一、逐行读取并解析输入
逐行读取并解析输入是处理复杂输入的推荐方法。使用fgets读取整行输入,然后使用sscanf或strtok解析输入。这种方法可以有效地处理输入错误,并且适用于各种输入格式。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 100
int main() {
int rows, cols;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
int array[rows][cols];
char line[MAX_LINE_LENGTH];
getchar(); // consume the newline character left in the buffer
printf("Enter the elements row by row:n");
for (int i = 0; i < rows; i++) {
if (fgets(line, sizeof(line), stdin) != NULL) {
char *token = strtok(line, " ");
for (int j = 0; j < cols; j++) {
if (token != NULL) {
array[i][j] = atoi(token);
token = strtok(NULL, " ");
}
}
}
}
printf("The array is:n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", array[i][j]);
}
printf("n");
}
return 0;
}
在上述代码中,我们首先读取行数和列数,然后使用fgets读取每一行的输入,并通过strtok解析输入,将数据存储到数组中。使用逐行读取可以有效地处理各种输入错误和格式问题。
二、使用scanf逐行读取
scanf函数是C语言中用于读取标准输入的常用函数。我们可以在循环中使用scanf逐行读取输入,并将数据存储到数组中。
#include <stdio.h>
int main() {
int rows, cols;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
int array[rows][cols];
printf("Enter the elements row by row:n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &array[i][j]);
}
}
printf("The array is:n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", array[i][j]);
}
printf("n");
}
return 0;
}
在上述代码中,我们首先读取行数和列数,然后在循环中使用scanf逐个读取输入并存储到数组中。这种方法简单直接,但对于复杂的输入格式处理能力有限。
三、使用fgets读取字符串并解析
fgets函数用于读取一行字符串,我们可以使用fgets读取整行输入,然后使用sscanf或字符串解析函数将数据转换为整数并存储到数组中。
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LENGTH 100
int main() {
int rows, cols;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
int array[rows][cols];
char line[MAX_LINE_LENGTH];
getchar(); // consume the newline character left in the buffer
printf("Enter the elements row by row:n");
for (int i = 0; i < rows; i++) {
if (fgets(line, sizeof(line), stdin) != NULL) {
for (int j = 0; j < cols; j++) {
sscanf(line, "%d", &array[i][j]);
// Move to the next integer in the line
while (*line != ' ' && *line != '