我正在尝试创建一个程序,其中用户首先输入矩阵的大小,然后是每个单元格是占用(o)还是未占用(。)。我如何编写它以便用户输入一整行的占用/未占用输入,而不是使用嵌套for循环逐个单元?
更新
有一个例子是逐个输入项目:
#include <stdio.h>
#define MAX_SIZE 100
int main(void)
{
char matrix[MAX_SIZE][MAX_SIZE] = { 0 };
int rows = 0, cols = 0;
while (rows < 1 || rows > MAX_SIZE)
{
printf("What is the number of rows? ");
scanf("%d", &rows);
}
while (cols < 1 || cols > MAX_SIZE)
{
printf("What is the number of columns? ");
scanf("%d", &cols);
}
// fill the matrix
printf("Please, fill the matrix by entering o for occupied or . for unoccupied cell (E for exit)\n");
int r, c, ch;
int fulfill = 1;
for (r = 0; r < rows && fulfill; r++)
{
for (c = 0; c < cols && fulfill; c++)
{
// clean the input bufer
while ((ch = getchar()) != '\n' && ch != EOF);
// read data
printf("cell [%d, %d] : ", r + 1, c + 1); // or just r, c if you prefer 0..(N-1) indexing
while (matrix[r][c] != 'o' && matrix[r][c] != '.' && matrix[r][c] != 'E')
{
scanf("%c", &matrix[r][c]);
}
if (matrix[r][c] == 'E')
{
fulfill = 0;
}
}
}
// output
printf("\nResult is:\n");
for (r = 0; r < rows; r++)
{
for (c = 0; c < cols; c++)
{
printf("%c", matrix[r][c]);
}
printf("\n");
}
}
答案 0 :(得分:1)
考虑以下示例:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char** matrix; // now it is a pointer and memory will be allocated after getting values of rows and columns
int rows = 0, cols = 0;
while (rows < 1)
{
printf("What is the number of rows (should be >= 1)? ");
scanf("%d", &rows);
}
while (cols < 1)
{
printf("What is the number of columns (should be >= 1)? ");
scanf("%d", &cols);
}
// part 1 for memory allocation
matrix = (char**)malloc(sizeof(char*) * rows);
// fill the matrix
printf("Please, fill the matrix by entering o for occupied or . for unoccupied cell (other chars will be ignored)\n");
int r, c, ch;
for (r = 0; r < rows; r++)
{
// part 2 for memory allocation - memory for each row
matrix[r] = (char*)malloc(sizeof(char) * cols);
for (c = 0; c < cols; c++)
{
// read while apropriate character was found
while ((ch = getchar()) != 'o' && ch != '.');
// save character to matrix
matrix[r][c] = ch;
}
}
// output
printf("\nResult is:\n");
for (r = 0; r < rows; r++)
{
for (c = 0; c < cols; c++)
{
printf("%c", matrix[r][c]);
}
printf("\n");
}
// free the memory
for (r = 0; r < rows; r++)
{
free(matrix[r]);
}
free(matrix);
}
这里数据存储在堆中(动态内存,由malloc
或其他类似函数分配),尽管使用相同的嵌套循环输入是不同的。看,它是如何工作的:
What is the number of rows (should be >= 1)? 3
What is the number of columns (should be >= 1)? 3
Please, fill the matrix by entering o for occupied or . for unoccupied cell (other chars will be ignored)
o.o
.o.
o.o
Result is:
o.o
.o.
o.o
用户可以使用Enter键逐行输入以开始新行,或者只为所有单元格逐个输入o
和.
(在任何情况下都将逐行填充)。不必要的元素以及不适当的字符(与o
和.
不同)将被忽略。 E.g:
What is the number of rows (should be >= 1)? 4
What is the number of columns (should be >= 1)? 5
Please, fill the matrix by entering o for occupied or . for unoccupied cell (other chars will be ignored)
ooZooCooXooOoo
......
........XXX
Result is:
ooooo
ooooo
.....
.....