gpt4 book ai didi

c - 将中间有逗号的整数扫描到二维数组中时出现问题

转载 作者:行者123 更新时间:2023-11-30 16:12:45 25 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序,它接受 axb:{{a,b,c},{d,e,f}...} 形式的二维矩阵,其中 a 确定行数, b 决定列数,子单元 {} 声明行,行的元素在 {} 之间声明为 a,b,c...。问题是该程序只接受元素之间没有逗号的矩阵,因此只有 axb:{{a b c},{d e f}...}} 格式的矩阵才有效。我希望程序能够接受变量之间带有逗号的输入。以下是引用代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
int a,b;
scanf("%dx%d:{", &a, &b);
int matrix[a][b];
int r,c;
for (r = 0; r < a; r++) {
scanf("{%d", &matrix[r][0]);
for(c = 1; c < (b -1); c++) {
scanf("%d", &matrix[r][c]);
}
scanf("%d},", &matrix[r][c]);
}
printf("%dx%d:{", b, a);
for (c = 0; c < (b - 1); c++) {
printf("{");
for(r = 0; r < (a - 1); r++) {
printf("%d,",matrix[r][c]);
}
printf("%d",matrix[r][c]);
printf("},");
}
printf("{");
for(r = 0; r < 3; r++) {
printf("%d,",matrix[r][c]);
}
printf("%d",matrix[r][c]);
printf("}");
printf("}\n");
return 0;
}

最佳答案

我要做的是扫描整个输入并随后进行处理。

#include <stdio.h>
#include <stdlib.h>


int main()
{
// scan the input matrix
int a, b;
char input[256];
scanf("%dx%d:%256[^\n]", &a, &b, input);

int mat[a][b];

// populate matrix:
char* p = input;
int i = 0;
while (p != input + 256)
{
// scan until the character is not a separator
if (*p == '{' || *p == '}' || *p == ',')
{
++p;
}
else
{
int n;
sscanf(p, "%d", &n);
mat[0][i] = n;
++i;

// scan until we find a separator character
while (p != input + 256 && (*p != '{' && *p != '}' && *p != ','))
{
++p;
}

if (i >= a*b)
break;
}
}
printf("your matrix:\n");
for (i = 0; i < a*b; ++i)
{
if (i % b == 0)
printf("\n");

printf("%d ", mat[0][i]);
}
printf("\n");

return 0;
}

输入和输出示例:

输入:
3x2:{{a, b},{c, d},{e, f}}

输出:

a b
c d
e f

其中 a、b、c、d、e 和 f 是数字(好吧,整数)。

然而,这可能不是一个优雅的解决方案,但它满足了您的要求。
至少可以给你一些想法。希望这能有所帮助。

注意:
当索引数组时,我使用了单个索引i。您可以执行此操作,因为此类数组无论如何都存储在一维数组中。然而这只是我的懒惰。欢迎指正。



如果这不是您想要的或者我犯了一些错误,请随时纠正我。可能误解了什么。

关于c - 将中间有逗号的整数扫描到二维数组中时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58258117/

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