atoi是把字符串转换为int型数据
atof是转换为float型
strtok是分隔字符串的
第一个例子用了sscanf, 没有用strtok
#include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<string.h> #define MAX_Line 2048 int main(){ FILE *Fr; Fr = fopen("test_Group_Box.txt", "r"); if(NULL == Fr){ printf("ERROR!\n"); return -1; } float t; char Test_N_arr[MAX_Line]; // char *Test_N_arr = (char*)malloc(sizeof(char) *MAX_Line); char str1[50], str2[50], str3[50]; // char str1, str2, str3; // "Read Each Line of Fr and assign each fields to three pointers" while (!feof(Fr)) { fgets(Test_N_arr, MAX_Line, Fr); sscanf(Test_N_arr, "%s\t%s\t%s", str1, str2, str3); t = atof(str3); printf("%s\t", str1); printf("%s\t", str2); if (strcmp(str1,"Group") == 0){ printf("%s\n", str3); }else { printf("%.2f\n", t); } } fclose(Fr); // free(Test_N_arr); return 0; }
另一个例子用了strtok
#include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<string.h> #define MAX_Line 2048 int main(){ FILE *Fr; Fr = fopen("test_Group_Box.txt", "r"); if(NULL == Fr){ printf("ERROR!\n"); return -1; } float t; char *Test_N_arr = (char*)malloc(sizeof(char) *MAX_Line); char *str; // "Read Each Line of Fr and assign each fields to three pointers" while (!feof(Fr)) { fgets(Test_N_arr, MAX_Line, Fr); str = strtok(Test_N_arr, "\t"); int i = 0; while(str != NULL){ if( i == 2){ if(strcmp(str, "Qual\n") == 0){ printf("%s", str); } else { t = atof(str); printf("%.2f\n", t); } }else { printf("%s\t", str); } i++; str = strtok(NULL, "\t"); } } fclose(Fr); free(Test_N_arr); return 0; }
时间: 2024-10-24 11:52:30