我有一个文本文件,提供用于在城市之间创建通信网络的输入数据。
N=12
C=[72,107,65,99,20,11,31,7,42,28,4, 31,10,57,37,71,18,17,73,39,14, 91,77,19,39,33,59,31,44,98, 71,66,36,23,10,100,93,41, 21,80,22,43,78,22,93, 77,81,49,62,89,19, 21,19,51,40,18, 102,92,28,51, 31,47,51, 73,38, 50]
R=[0.81,0.88,0.83,0.90,0.98,0.93,0.86,0.91,0.92,0.86,0.80, 0.91,0.87,0.78,0.83,0.90,0.93,0.87,0.79,0.99,0.94, 0.88,0.98,0.97,0.96,0.92,0.81,0.99,0.92,0.91, 0.80,0.88,0.87,0.93,0.90,0.99,0.98,0.91, 0.89,0.80,0.92,0.93,0.83,0.87,0.99, 0.97,0.91,0.89,0.99,0.94,0.90, 0.87,0.89,0.95,0.85,0.96, 0.99,0.79,0.88,0.81, 0.84,0.97,0.77, 0.83,0.93, 0.99]
a_b=1
Req_Reliability = 0.5
Req_Cost = 267
其中: N 是网络中的城市数量 和 C & R 对称N×N矩阵分别给出了在两个城市之间实现连接的成本和可靠性。
N 可以变化,只要它是大于2的整数。并且给定的矩阵C& R会相应变化。
从文本文件开始,由于矩阵是对称的,所以只给出了矩阵的上半部分,所有索引为i = j的元素都应该为0,这样文本文件中矩阵C的格式就是这样:
C=[C(1-2),C(1-3),...,C(1-12),whitespaceC(2-3),C(2-4),...,C(2-12),...,whitespaceC(11-12)]
with C(IDstartCity-IDstopCity)
文本文件中的空格表示对下一行的更改,相同的结构适用于矩阵R.
我想要做的是在我的C程序中将每个变量分配给它的匹配。 虽然我对如何将12分配给N有了一个想法,但我对于如何将文本文件中的矩阵C和R的奇怪结构分配给C程序中的矩阵感到无能为力。
int main(int argc, const char * argv[]) {
FILE *finput;
char var_name[5];
int value = 0;
finput = fopen("Prj1_input.txt", "r");
//Inputs Start
int N; //Number of cities
//Cost Array
int **C = malloc(N * sizeof(int*));
for (i = 0; i < N; i++) {
C[i] = malloc(N * sizeof(int));
memset(C[i], 0, N * sizeof(int));
}
//Reliability Array
double **R = malloc(N * sizeof(double*));
for (i = 0; i < N; i++) {
R[i] = malloc(N * sizeof(double));
memset(R[i], 0, N * sizeof(double));
}
int con_cost; //Connection cost between 2 cities
double con_reliability; //Connection reliability between 2 cities
int a_b; //0 is type a, 1 is type b
double Req_reliability, Req_cost; //reliability for type a, cost for type b
//Inputs Stop
fscanf(finput, "%c=%d", var_name, &value);
printf("%s %d\n", var_name, value);
fclose(finput);
return 0;
}
我想我可以使用两个for循环,当我在文本文件中找到一个空格时,我会增加行,但我完全不知道如何处理文本文件。
现在,如果我在//输入开始和//输入停止之间注释掉所有内容,那么输出就是 N 12
由于
答案 0 :(得分:0)
以C为例,首先制作一个大小为N的数组:
int **C = malloc(N * sizeof(int*));
for (i = 0; i < N; i++) {
C[i] = malloc(N * sizeof(int));
memset(C[i], 0, N * sizeof(int));
}
然后循环并分配给矩阵:
char *s = "<the string inside the [...]>";
char *p = s, *e;
for (i = 0; i < N; i++) {
for (j = i + 1; j < N; j++) {
e = strchr(p, ',');
*e = '\0';
C[i][j] = atoi(p);
p = e + 1;
}
}