【发布时间】:2018-03-07 18:17:23
【问题描述】:
我是 C 的新手,正在尝试制作一个小程序。
基本上,它是一个程序,它从文本文件中获取元素名称、组、句点(不科学正确)编号。然后将元素名称插入二维字符串数组(代码中的elmName),将元素编号插入二维整数数组(elmNumber),然后将它们打印为元素周期表。
但是当我尝试运行它时,程序会获取它读取的最后一个元素名称并将其分配给 2d 字符串数组 (elmName) 中的每个元素。
代码如下:
char* elmName[18][5];
int elmNumber[18][5];
//AtomNumber[Group][Period]
int iGroupCount = 18;
int iPeriodCount = 5;
for(int i=0;i<iPeriodCount;i++){
for(int j=0;j<iGroupCount;j++){
elmNumber[j][i] = 0;
}
}
printf("\n");
for(int i=0;i<iPeriodCount;i++){
for(int j=0;j<iGroupCount;j++){
printf("%d ", elmNumber[j][i]);
}
printf("\n");
}
int g,p,num;
//g = Group
//p = Period
//num = Atom no.
int tempNum;
char tempName[2];
for(int i=0;i<iPeriodCount;i++){
for(int j=0;j<iGroupCount;j++){
//if there is not an element at this group and period name it '*'
elmName[j][i] = "*";
}
}
FILE *fs = fopen("element.txt" , "r");
while(!feof(fs)){
fscanf(fs ,"%d\t%d\t%d\t%s\n" , &g , &p , &tempNum , tempName);
printf("%d\t%d\t%d\t%s\n" , g , p , tempNum , tempName);
if( elmName[g][p] == "*"){
elmNumber[g][p] = tempNum;
elmName[g][p] = tempName;
}
//g = group No
//p = period No
}
fclose(fs);
这是它读取的文本文件:
0 0 1 H
17 0 2 He
0 1 3 Li
1 1 4 Be
12 1 5 B
13 1 6 C
14 1 7 N
15 1 8 O
16 1 9 F
17 1 10 Ne
0 2 11 Na
1 2 12 Mg
12 2 13 Al
13 2 14 Si
14 2 15 P
15 2 16 S
16 2 17 Cl
如果您有解决方案,请提供帮助。 :)
【问题讨论】:
-
使用字符串比较方法比较字符串。
标签: c arrays string multidimensional-array