gpt4 book ai didi

c - 使用 getchar 读取用户输入并创建二维矩阵

转载 作者:行者123 更新时间:2023-11-30 16:31:01 24 4
gpt4 key购买 nike

提示用户输入字符串。

输入:1 2 3; 4 5 6; 7 8 9

输出:

1 2 3

4 5 6

7 8 9

同一行上的条目由一个空格分隔。行之间用分号和空格分隔。我需要使用 getchar 函数手动解析输入行,以便我可以创建这个矩阵并用它执行其他操作。

甚至不知道从哪里开始。我正在考虑使用一个循环,每次读取分号时都会递增。但我真的根本不知道如何使用getchar!

while((input1 = getchar())!= '\n')
{
if((input1 > '0') || (input1 < '9')){
matrixA[row][col] = input1;
if(input1 == ' '){
col++;
matrixA[row][col] = input1;
}
if(input1 == ';'){
matrixA[row][col]=input1;
row++;
}

编辑:此代码打印(空)

最佳答案

经过一些进一步的改进:它仅打印用户输入的第一个字符或前两个字符,具体取决于遇到第一个分号之前的输入数量。我的打印语句在循环之外。

char matrixA[100][100];

char matrixB[100][100];
char input1, input2;
int row=0, col=0, num = 0;

printf("Enter matrix A:\n");

while(input1 != '\n'){

input1 = getchar();

if((input1 > '0') && (input1 < '9') && (input1 != ' ') && (input1 != ';')){
//num = (num*10) + (input1 - '0');
matrixA[row][col] = input1;
}

if(input1 == ' '){
col++;
}
if (input1 == ';'){
row++;
}
}

关于c - 使用 getchar 读取用户输入并创建二维矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50826970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com