【问题标题】:Problem Scanning Integers with Comma Between Them into a 2d Array将带有逗号的整数扫描成二维数组时出现问题
【发布时间】:2019-10-06 14:16:00
【问题描述】:

我正在尝试编写一个 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;
}

【问题讨论】:

  • 你的问题是什么?
  • 如果有scanf("%d", &amp;matrixelement),请使用if (scanf("%d%c", &amp;matrixelement, &amp;separator) != 2) /* error */;,其中separatorchar 类型的对象。 separator 将有空格或逗号。
  • 当你可以使用"{%d"作为第一个元素时,为什么你不能使用",%d"作为下一个元素呢?顺便说一句,你有没有想过如果 a 等于 1 会发生什么?

标签: c arrays scanf


【解决方案1】:

我要做的是扫描整个输入,然后再使用它。

#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。你可以这样做,因为像这样的数组无论如何都存储在一维数组中。然而,这只是我的懒惰。请随时更正。



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

【讨论】:

  • 谢谢!这不是我需要的代码,但我修改了它,因为它是一个很好的起点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-03-09
相关资源
最近更新 更多