Reads a file (input.txt) which contains several player data, including ID, Name, Age and Score.
Parse these data into struct with the format shown below.
struct
{
id (integer number)
name (string)
age (integer number)
score (floating number)
}
Reads another file (cmd.txt) which contains several numbers, iterate through each number and show the player data if the ID matched the number; otherwise print “Player data not found.” as the output.
範例輸入:
(Input File: input.txt)
3
12,Samina Hubbard,22,852.4
2,Idris Lindsey,30,1234.5
21,Briony Mullins,37,2123.5
(Command File: cmd.txt)
12
21
0
2
3
範例輸出:
程式碼:
#include <stdio.h> #include <string.h> #include "FileHandler.h" int main() { int n = 0, i_now = 0; char *str = readAllTextFromFile("./input.txt"); while (str[i_now] != '\n') //read case number { n = (str[i_now] - '0') + n * 10; i_now++; } i_now++; //skip new line struct data { int id; char name[50]; int age; char score[50]; }; struct data player[100]; for (int i = 0; i < n; i++) //read player data { for (int j = 0; j < 50; j++) player[i].name[j] = NULL; for (int j = 0; j < 50; j++) player[i].score[j] = NULL; int id = 0, len1 = 0, age = 0, len2 = 0; while (str[i_now] != ',') { id = id * 10 + str[i_now] - '0'; i_now++; } player[i].id = id; i_now++; while (str[i_now] != ',') { player[i].name[len1] = str[i_now]; i_now++; len1++; } i_now++; while (str[i_now] != ',') { age = age * 10 + str[i_now] - '0'; i_now++; } player[i].age = age; i_now++; while (str[i_now] != '\n') { player[i].score[len2] = str[i_now]; i_now++; len2++; } i_now++; if (str[i_now] == NULL) break; } str = readAllTextFromFile("./cmd.txt"); i_now = 0; while (str[i_now]!=NULL) { int num = 0, check = 0; while (str[i_now] != '\n'&&str[i_now]!=NULL) { num = num * 10 + str[i_now] - '0'; i_now++; } i_now++; for (int i = 0; i < n; i++) { if (player[i].id == num) { printf("ID: %d\n", player[i].id); printf("Name: %s\n", player[i].name); printf("Age: %d\n", player[i].age); printf("Score: %s\n\n", player[i].score); check = 1; break; } } if (check == 0) printf("Player not found\n\n"); if (str[i_now]==NULL) break; } system("pause"); return 0; }
沒有留言:
張貼留言