gpt4 book ai didi

c - 在 C/C++ 中使用标准输入输入

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

我必须读取图形输入(一次全部)(下面的示例):

6 8 //no of vertices, edges
0 1 2 //connectivity from vertex 0 to vertex 1, with weight 2
0 2 1
0 4 2
1 2 4
2 3 5
3 4 5
4 1 2
4 5 5

动态读取输入的最佳方式是什么。我必须一次阅读以上所有内容。我需要动态读取它,因为边和顶点的数量可以改变,最大值为 10000。以下不起作用:

int *twod_array; 
int N,M; //no of vertices, edges
scanf("%d %d", &N, &M);
twod_array = (int *)malloc(sizeof(int)*N*M); //where N = no of rows, M = no of cols
for(i=0; i < N; i++) {
for(j=0; j < M; j++) {
scanf("%d",&twod_array[i*M +j]);
}
}
for(i=0; i < N; i++) {
for(j=0; j < M; j++) {
if(twod_array[i*M +j] == "\0") {
twod_array[i*M +j] = 0;
}
}
}

此外,这是 C/C++ 中图形的最佳方式还是使用结构更好,因为将完成遍历。

最佳答案

就加载数据而言,有很多方法。一种方法是创建一个connectivity 结构,并根据数据文件第一行中的边值数量动态分配一个数组:

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

struct connectivity {
int source;
int sink;
int weight;
};

int main() {
int num_verts = 0;
int num_edges = 0;
struct connectivity *edges = NULL;
int i = 0;

scanf("%d %d\n", &num_verts, &num_edges);

edges = malloc(sizeof (struct connectivity) * num_edges);

for (i = 0; i < num_edges; i++) {
scanf("%d %d %d\n", &(edges[i].source),
&(edges[i].sink),
&(edges[i].weight));
}

// use edges here

free(edges);
}

另外,请使用更易读的变量名!

关于c - 在 C/C++ 中使用标准输入输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33460118/

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