C 二维阵列打印错误

C 二维阵列打印错误,c,arrays,for-loop,multidimensional-array,traveling-salesman,C,Arrays,For Loop,Multidimensional Array,Traveling Salesman,我在正确打印旅行推销员问题的2D数组时遇到问题。我使用输入重定向从文本文件获取输入。该文件包含城市和具有城市之间距离的圆弧。这里有一个小例子 c 1 c 2 a 1 2 1400 设置阵列并绘制城市之间的距离后,我使用嵌套for循环打印阵列,但看起来是这样的 0 1 2 3 4 5 1 0 1400 1800 4000 3500 2 1 0

我在正确打印旅行推销员问题的2D数组时遇到问题。我使用输入重定向从文本文件获取输入。该文件包含城市和具有城市之间距离的圆弧。这里有一个小例子

c 1
c 2
a 1 2 1400
设置阵列并绘制城市之间的距离后,我使用嵌套for循环打印阵列,但看起来是这样的

    0       1       2       3       4       5

    1       0       1400    1800    4000    3500

    2       1       0       0       3400    3600

    3       1800    1200    0       2300    0

    4       4000    3400    2300    0       2100

    5       3500    3600    0       2100    0
编辑:我想让它看起来像这样

    0       1       2       3       4       5

    1       0       1400    1800    4000    3500

    2       1400    0       1200    3400    3600

    3       1800    1200    0       2300    2700

    4       4000    3400    2300    0       2100

    5       3500    3600    2700    2100    0
我尝试以不同的方式操纵for循环,但我似乎无法找出我的问题在循环中的什么地方,或者它是否在代码中的其他地方

// Sets up the array
int CityArray [6][6] = { {0, 0, 0, 0, 0, 0},
                         {0, 0, 0, 0, 0, 0},
                         {0, 0, 0, 0, 0, 0},
                         {0, 0, 0, 0, 0, 0},
                         {0, 0, 0, 0, 0, 0},
                         {0, 0, 0, 0, 0, 0}
                       };

int main(void) // Takes in a variable number of arguments
{
    // Sets a string input for the city
    char Cbuffer[32];
    char *b = Cbuffer;
    size_t cbufsize = 32;
    size_t cinput;

    // Other vairables
    int x = 1; // used to go through the array
    int n1, n2, n3, n4, cost; // variables to store the value pulled the cost from the arc

    // Reads in the city and sets the prices for each arc
    while((cinput = getline(&b, &cbufsize, stdin)) != -1)
    {
        if (Cbuffer[0] == 'c')
        {
            // Stores the last element as a digit to CityArray
            if (Cbuffer[2] >= '0' && Cbuffer[2] <= '9')
            {
                CityArray[x][0] = Cbuffer[2] - '0';
                int z = CityArray[x][0];
                // Flips it
                CityArray[0][x] = Cbuffer[2] - '0';
                z = CityArray[0][x];
                // printf("CityArray[%d] is '%d' \n", x, z);
                x++;
            }
        }
        else if (Cbuffer[0] == 'a')
        {
            int y = 1;
            // I know this looks ugly but it's the only way I could think of getting the prices
            if ((Cbuffer[6] >= '0' && Cbuffer[6] <= '9') && (Cbuffer[7] >= '0' && Cbuffer[7] <= '9') &&
                    (Cbuffer[8] >= '0' && Cbuffer[8] <= '9') && (Cbuffer[9] >= '0' && Cbuffer[9] <= '9'))
            {
                for (x = 1; x < 6; x++)
                {
                    for (y; y < 6; y++)
                    {   // converts the char to a int
                        n1 = CityArray[x][6] = Cbuffer[6] - '0';
                        n2 = CityArray[x][7] = Cbuffer[7] - '0';
                        n3 = CityArray[x][8] = Cbuffer[8] - '0';
                        n4 = CityArray[x][9] = Cbuffer[9] - '0';
                    }
                } // sets all converted ints to = cost
                cost = (n1 * 1000) + (n2 * 100) + (n3 * 10) + (n4 * 1);
                x++;
            }
            // Checks where the arc is located and plots the distance of the trip
            if (Cbuffer[2] == '1')
            {
                if (Cbuffer[4] == '2')
                {
                    CityArray[1][2] = cost;
                    CityArray[2][1] = cost;
                }
                else if (Cbuffer[4] == '3')
                {
                    CityArray[1][3] = cost;
                    CityArray[3][1] = cost;
                }
                else if (Cbuffer[4] == '4')
                {
                    CityArray[1][4] = cost;
                    CityArray[4][1] = cost;
                }
                else if (Cbuffer[4] == '5')
                {
                    CityArray[1][5] = cost;
                    CityArray[5][1] = cost;
                }
            }
            else if (Cbuffer[2] == '2')
            {
                if (Cbuffer[4] == '3')
                {
                    CityArray[2][3] = cost;
                    CityArray[3][2] = cost;
                }
                else if (Cbuffer[4] == '4')
                {
                    CityArray[2][4] = cost;
                    CityArray[4][2] = cost;
                }
                else if (Cbuffer[4] == '5')
                {
                    CityArray[2][5] = cost;
                    CityArray[5][2] = cost;
                }
            }
            else if (Cbuffer[2] == '3')
            {
                if (Cbuffer[4] == '4')
                {
                    CityArray[3][4] = cost;
                    CityArray[4][3] = cost;
                }
            else if (Cbuffer[4] == '5')
            {
                    CityArray[4][5] = cost;
                    CityArray[5][4] = cost;
                }
            }
            else if (Cbuffer[2] == '4')
            {
                if (Cbuffer[4] == '5')
                {
                    CityArray[4][5] = cost;
                    CityArray[5][4] = cost;
                }
            }
        }   
    }

    // Prints the array
    int i, j;
    printf("\n\nThe cost list is:\n\n");
    for(i = 0; i < 6;i ++)
    {
        printf("\n\n");
        for(j = 0; j < 6; j++)
        {
            printf("\t%d", CityArray[i][j]);
        }
        printf("\n");
    }

    return 0;
}
//设置数组
int CityArray[6][6]={{0,0,0,0,0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0}
};
int main(void)//接受数量可变的参数
{
//设置城市的字符串输入
char-Cbuffer[32];
char*b=Cbuffer;
大小\u t cbufsize=32;
大小输入;
//其他虚荣
int x=1;//用于遍历数组
int n1,n2,n3,n4,cost;//用于存储从arc中提取的成本值的变量
//在城市中阅读,并设定每个弧的价格
while((cinput=getline(&b,&cbufsize,stdin))!=-1)
{
if(Cbuffer[0]=“c”)
{
//将最后一个元素作为数字存储到CityArray
如果(Cbuffer[2]>='0'&&Cbuffer[2]您的问题在这里:

            for (x = 1; x < 6; x++)
            {
                for (y; y < 6; y++)
                {   // converts the char to a int
                    n1 = CityArray[x][6] = Cbuffer[6] - '0';
                    n2 = CityArray[x][7] = Cbuffer[7] - '0';
                    n3 = CityArray[x][8] = Cbuffer[8] - '0';
                    n4 = CityArray[x][9] = Cbuffer[9] - '0';
                }
            } // sets all converted ints to = cost
            cost = (n1 * 1000) + (n2 * 100) + (n3 * 10) + (n4 * 1);
            x++;
代码仍然存在许多问题。特别是,城市和距离的解析非常有限。如果一个城市的成本不是四位数,会发生什么?如果第一个城市的数字大于第二个城市,会发生什么

您还可以将ASCII转换为城市的一位数整数:

        int from = Cbuffer[2] - '0';
        int dest = Cbuffer[4] - '0';

        CityArray[from][dest] = cost;
        CityArray[dest][from] = cost;
这将省去很多代码。与其对所有可能的代码进行硬编码,不如将精力花在编写有意义的错误消息上,例如,如果某个城市的id超出范围

你也应该考虑使用标准的方法来解析输入。<代码> GETLION>代码>结合<代码> SCANF可能是一个很好的方法。 编辑:下面是输入的一个示例实现。它最多可以包含10个城市,由一个可能是数字的字符标识。它对

c
a
行的确切格式没有任何限制,并且还跟踪变量
ncitiy
中的实际城市数。它接受空行和以
#
开头的行作为非命令

尽管存在大量错误检查,但此程序比您的程序略短。如下所示:

#define _GNU_SOURCE

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

#define MAX 10


int find(int array[], int n, int x)
{
    for (int i = 0; i < n; i++) {
        if (array[i] == x) return i;
    }

    return -1;
}

int main(void)
{
    int cost[10][10] = {{0}};       // cost matrix
    int id[MAX];                    // city id; can be any character
    int ncity = 0;                  // number of cities

    char *line = NULL;
    size_t nline = 0;
    int error = 0;

    while (getline(&line, &nline, stdin) != -1) {
        char c1, c2;
        int c;

        if (sscanf(line, " c %c", &c1) == 1) {
            if (find(id, ncity, c1) != -1) {
                fprintf(stderr, "Duplicate city id %c.\n", c1);
                error = 1;
                break;
            } else if (ncity >= MAX) {
                fprintf(stderr, "Maximum number of cities exceeded\n");
                error = 1;
                break;
            } else {
                id[ncity++] = c1;
            }
            continue;
        }

        if (sscanf(line, " a %c %c %d\n", &c1, &c2, &c) == 3) {
            int from = find(id, ncity, c1);
            int dest = find(id, ncity, c2);

            if (from < 0) {
                fprintf(stderr, "Unknown city id %c.\n", c1);
                error = 1;
                break;
            }

            if (dest < 0) {
                fprintf(stderr, "Unknown city id %c.\n", c2);
                error = 1;
                break;
            }

            cost[from][dest] = c;
            cost[dest][from] = c;

            continue;
        }

        if (sscanf(line, " %c", &c1) == 1 && c1 != '#') {
            fprintf(stderr, "Unknown command: %s", line);
            error = 1;
            break;
        }
    }

    free(line);

    if (error) {
        fprintf(stderr, "Errors in input. Aborting.\n");
        exit(1);
    }

    printf("%8s", "");
    for (int j = 0; j < ncity; j++) {
        printf("%8c", id[j]);
    }
    puts("");

    for(int i = 0; i < ncity; i ++)
    {
        printf("%8c", id[i]);
        for (int j = 0; j < ncity; j++) {
            printf("%8d", cost[i][j]);
        }
        puts("");
    }
    puts("");

    return 0;
}
定义GNU源
#包括
#包括
#定义最大值10
int find(int数组[],int n,int x)
{
对于(int i=0;i=最大值){
fprintf(stderr,“超过的最大城市数”);
误差=1;
打破
}否则{
id[ncity++]=c1;
}
继续;
}
如果(sscanf(行“a%c%c%d\n”、&c1、&c2、&c)==3){
int from=查找(id、ncity、c1);
int dest=查找(id、ncity、c2);
如果(从<0开始){
fprintf(标准,“未知城市id%c.\n”,c1);
误差=1;
打破
}
if(dest<0){
fprintf(标准,“未知城市id%c.\n”,c2);
误差=1;
打破
}
成本[从][目的地]=c;
成本[dest][from]=c;
继续;
}
如果(sscanf(行“%c”、&c1)==1&&c1!='#'){
fprintf(stderr,“未知命令:%s”,第行);
误差=1;
打破
}
}
自由线;
如果(错误){
fprintf(stderr,“输入错误。正在中止。\n”);
出口(1);
}
printf(“%8s”,”);
对于(int j=0;j
“但它看起来像这样。”-你能解释一下你希望它看起来怎么样吗?让我编辑我的问题!如果缓冲区不够大,那么
getline
释放现有的缓冲区并分配一个新的,然后返回。因此你不应该通过
Cbuffer
,因为释放缓冲区是一个错误;你不应该测试
Cbuffer[0]=='c'
等,因为行可能已重新分配。相反,您可以将
b=NULL
设置为开始,并使用
b[0]
等(或者为了避免大量键入,请去掉
b
并使用
char*Cbuffer=NULL;
)。[可能与您的问题无关,因为您的文件行都小于32行,但这是一颗定时炸弹]感谢您的建议,我没有意识到如果我处理的行数大于32行,可能会导致问题。谢谢,您的建议奏效!最初我认为我的问题出在代码的那一部分,但我没有解决
#define _GNU_SOURCE

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

#define MAX 10


int find(int array[], int n, int x)
{
    for (int i = 0; i < n; i++) {
        if (array[i] == x) return i;
    }

    return -1;
}

int main(void)
{
    int cost[10][10] = {{0}};       // cost matrix
    int id[MAX];                    // city id; can be any character
    int ncity = 0;                  // number of cities

    char *line = NULL;
    size_t nline = 0;
    int error = 0;

    while (getline(&line, &nline, stdin) != -1) {
        char c1, c2;
        int c;

        if (sscanf(line, " c %c", &c1) == 1) {
            if (find(id, ncity, c1) != -1) {
                fprintf(stderr, "Duplicate city id %c.\n", c1);
                error = 1;
                break;
            } else if (ncity >= MAX) {
                fprintf(stderr, "Maximum number of cities exceeded\n");
                error = 1;
                break;
            } else {
                id[ncity++] = c1;
            }
            continue;
        }

        if (sscanf(line, " a %c %c %d\n", &c1, &c2, &c) == 3) {
            int from = find(id, ncity, c1);
            int dest = find(id, ncity, c2);

            if (from < 0) {
                fprintf(stderr, "Unknown city id %c.\n", c1);
                error = 1;
                break;
            }

            if (dest < 0) {
                fprintf(stderr, "Unknown city id %c.\n", c2);
                error = 1;
                break;
            }

            cost[from][dest] = c;
            cost[dest][from] = c;

            continue;
        }

        if (sscanf(line, " %c", &c1) == 1 && c1 != '#') {
            fprintf(stderr, "Unknown command: %s", line);
            error = 1;
            break;
        }
    }

    free(line);

    if (error) {
        fprintf(stderr, "Errors in input. Aborting.\n");
        exit(1);
    }

    printf("%8s", "");
    for (int j = 0; j < ncity; j++) {
        printf("%8c", id[j]);
    }
    puts("");

    for(int i = 0; i < ncity; i ++)
    {
        printf("%8c", id[i]);
        for (int j = 0; j < ncity; j++) {
            printf("%8d", cost[i][j]);
        }
        puts("");
    }
    puts("");

    return 0;
}