gpt4 book ai didi

c - 从文件中读取输入并以 C 中的特定格式存储在数组中

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:17 25 4
gpt4 key购买 nike

我想从一个文本文件中读取并显示一些输出

输入文件格式:

0 0 3         
0 1 2
1 3 4
2 1 4
3 2 3
3 1 2
4 3 4

每行的第一个数字表示特定的一天(第 0 到 4 天),每行的第二个和第三个数字表示当天相互发送消息的参与者。我编写了以下 C 代码来显示每天的参与 Actor :

我的示例代码:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define B 5 // number of days
#define A 5 // number of total actors

main()
{
FILE *fp;
int end = 0;
int day1, day, i, j, k1, k2;
int esin[A][A];
for (i = 0; i < A; i++) // initializing array
{
for (j = 0; j < A; j++)
{
esin[i][j] = 0;
}
}
fp = fopen("test.txt", "r"); // the file contains the input
if (fp == NULL)
{
printf("\nError - Cannot open the designated file\n");
}

while (end == 0)
{
fscanf(fp, "%d", &day);
day1 = day; // day1 for comparing
while (day1 == day)
{
if (feof(fp))
{
end = 1;
break;
}
fscanf(fp, "%d %d", &k1, &k2);

esin[k1][k2] = 1;// edge creation
esin[k2][k1] = 1;// edge creation

fscanf(fp, "%d", &day);
}

printf("\nday: %d", day1); // for printing output of a particular day
for (i = 0; i < A; i++)
{
for (j = 0; j < A; j++)
{
if (esin[i][j] == 0)
continue;
else
printf("\n%d and %d have an edge", i, j);
}
}
for (i = 0; i < A; i++)
{
for (j = 0; j < A; j++)
{
esin[i][j] = 0;
}
}
}
}

但我没有得到实际输出。例如,我想得到如下输出:

day 0
0 and 3 have an edge
1 and 2 have an edge
day 1
3 and 4 have an edge
day 2
1 and 4 have an edge
day 3
2 and 3 have an edge
1 and 2 have an edge
day 4
3 and 4 have an edge

但是我没有得到这个。我得到:

day 0
0 and 3 have an edge
1 and 2 have an edge
day 3
4 and 2 have an edge
day 4
3 and 2 have an edge
day 3
1 and 2 have an edge
day 3
4 and 2 have an edge

上面的代码有什么问题吗?我需要进行哪些更正才能获得上述类似输出?

最佳答案

在这一行

if(esin[i][j]=0)

你正在分配,但你想比较:

if(esin[i][j] == 0)

关于c - 从文件中读取输入并以 C 中的特定格式存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39255681/

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