将带有名称和结果的文本文件放入 ac 程序以按结果排序。如何忽略下面文件中的错误插入,例如数字 8?
.txt 代码如下所示
保罗 35.6
彼得 53.4
杰克 23.0
8
步长 0.0
阿曼达 43.5
第一个数组是 arrayName[],第二个是 arrayResult[],arrayFail[] 是 0.0 点。
#define ARRAYSIZE 15 // THIS IS THE MACRO FOR DEFINING THE ARRAY SIZE
#define STRSIZ 40 // THIS IS THE MACRO FOR DEFINING THE STRING SIZE
int main(){
/* Declaration of variables */
int i, j, n, f = 0;
float a, m =0;
char c;
/* Defining the arrays for names and results */
char arrayName[ARRAYSIZE][STRSIZ];
char arrayTemp[ARRAYSIZE][STRSIZ];
char arrayFail[ARRAYSIZE][STRSIZ];
float arrayResults[ARRAYSIZE];
n = ARRAYSIZE;
/* Code to open file and check list for validation */
FILE *fp;
fp = fopen("List.txt", "r"); //Opens the file
while ((c = fgetc(fp)) != EOF){
if (c == '\n')
m = m +1;
}
n = m;
// Close the file
fclose(fp);
/* Validates the name list */
while( n <= 0 || n > 15){
printf("\nThe list is invalid. It must be atleast one name and a maximum of 15 names. Please edit List.txt and re-run the program\n");
return 0;
}
/* Here the program scans the list from the text file */
for(i = 0; i < n; i++){
scanf("%s %f", arrayName[i], &arrayResults[i]);
}
/* Printing out the competitors list */
printf("The competitors: ");
for(i = 0; i < n - 1; i++){
printf("%s, ", arrayName[i]);
}
for(i = n - 1; i < n; i++){
printf("%s.", arrayName[i]);
}
/* The array is ordered */
for(i = 0; i < n; i++){
for(j = i + 1; j < n; j++){
if( arrayResults[i] < arrayResults[j]){
a = arrayResults[i];
strcpy(arrayTemp[i], arrayName[i]);
arrayResults[i] = arrayResults[j];
strcpy(arrayName[i], arrayName[j]);
arrayResults[j] = a;
strcpy(arrayName[j], arrayTemp[i]);
}
}
}
/* Printing out the Top 3 */
printf("\n\nThe Top 3:\n");
for(i = 0; i < 3; i++)
printf("No%d: %s with %.1f\n", i+1, arrayName[i], arrayResults[i]);
/* Failed competitors and their names are detected and stored */
for(i = 0; i < n; i++){
if( arrayResults[i] == 0 ){
strcpy(arrayFail[f], arrayName[i]);
f++;
}
}
/* Printing out the failed competitors */
printf("\nThe failed competitors were: ");
for(i = 0; i < f - 1; i++){
printf("%s, ", arrayFail[i]);
}
printf("%s.", arrayFail[f - 1]);
printf("\n");
return 0;
}
您可以在收集期间测试每个条目的有效性,并在测试失败时绕过它(您可以根据自己的目标调整测试,这里我们只测试字符串不为空):
int countEntry = 0;
for(i = 0; i < n; i++){
scanf("%s %f", arrayName[i], &arrayResults[i]);
// If name or score is null, decrease i to ignore that entry
if (arrayName[i][0] == 0 || arrayResults[i][0] == 0) i--;
// Else counts the entry
else countEntry++;
}
那么你应该控制至少有一个有效的条目:
if(countEntry == 0) {
printf("\nThe list is invalid. It must be atleast one name. Please edit List.txt and re-run the program\n");
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句