elements.txt :
___________________________
Hydorgen, H, 1, 1.0008
Helium, He, 2,4.003
Lithium, Li, 3, 5.939
Beryllium, Be, 4, 9.012
Boron, B, 5, 10.811
Carbon, C, 6,12.011
Nitrogen, N, 7, 14.007
Oxygen, O, 8, 15.999
Fluorine, F, 9, 18.998
Neon, Ne, 10, 20.183
经程序处理后:
Element (symbol) Atomic Weight
=============================================================
1. Hydorgen (H) 1.001
2. Helium (He) 4.003
3. Lithium (Li) 5.939
4. Beryllium (Be) 9.012
5. Boron (B) 10.811
6. Carbon (C) 12.011
7. Nitrogen (N) 14.007
8. Oxygen (O) 15.999
9. Fluorine (F) 18.998
10. Neon (Ne) 20.183
请按任意键继续. . .
/* main.c */
#include
#include
#define ElementFile "elements.txt"
#define MaxElementName 15
#define MinSymbolName 2
int main()
{
FILE *infile;
char elementName[MaxElementName+1];
char elementSymbol[MinSymbolName+1];
char namebuf[20];
int atomicNumber;
double atomicWeight;
char termch;
int nscan;
infile = fopen(ElementFile, "r");
if (infile == NULL) {
perror("Can't open");
system("pause");
exit(1);
}
printf(" Element (symbol) Atomic Weight \n");
printf("=============================================================\n");
while (1)
{
nscan = fscanf(infile, "%15[^,], %2[^,], %d, %lf%c",
elementName, elementSymbol,
&atomicNumber, &atomicWeight,
&termch);
if (nscan == EOF)
break;
if (nscan != 5 || termch != '\n')
perror("Improper file format");
sprintf(namebuf, "%s (%s)", elementName, elementSymbol);
printf("%3d. %-20s %8.3f\n", atomicNumber, namebuf, atomicWeight);
}
system("pause");
return 0;
}
阅读(369) | 评论(0) | 转发(0) |