我已經寫了一個快速的解析器,這讀取一個int跳過非字母字符,存儲所有字符,直到找到那麼數字解析浮動
我已經後stdin
解析做任何修改。 標準輸入:
45 foo bar 45.69
45, toto, 78.5
標準輸出:
文件內容:
45,foo bar,45.69
45,toto,78.50
PROG:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
int id;
char name[256]; /* use aligned structures*/
float grade;
} Student;
int main() {
Student s;
FILE *fp;
char buf[BUFSIZ];
char *p;
int i = 0;
fp = fopen("student.txt", "a+");
printf("Give id name and grade\n");
fgets(buf, sizeof(buf), stdin);
p = buf;
/* get id */
s.id = strtol(p, &p, 10);
if (!s.id) {
fprintf(stderr, "Bad id");
return -1;
}
/* skip non alpha char between int and name*/
while (!isalpha(*p)) {
p++;
}
/*copy name */
while (!isdigit(*p)) {
s.name[i++] = *p++;
}
if (i == 0) {
fprintf(stderr, "Bad name");
return -1;
}
s.name[i] = '\0';
i--;
/*remove trailing char at the end of the name */
while(!isalpha(s.name[i])) {
s.name[i--] = '\0';
}
/* parse grade */
s.grade = strtof(p, &p);
fprintf(fp,"%d,%s,%.2f\n",s.id,s.name,s.grade);
fclose(fp);
fp = fopen("student.txt","r");
if(fp != NULL) {
while((fscanf(fp,"%d,%299[^,],%f", &s.id,s.name,&s.grade)) == 3) {
printf("ID:%d\n",s.id);
printf("NAME:%s\n",s.name);
printf("GRADE:%.2f\n",s.grade);
}
fclose(fp);
} else {
perror("student.txt");
}
return 0;
}
我不明白輸入是來自文件還是來自stdin? –
我將數據輸入到名爲student.txt的文本文件中,如何刪除顯示在帖子中的額外空間。 –
請更清晰地定義您的需求。文件中還有其他空格。那麼你需要刪除哪些?其他地方是否可以有不需要的空間?它恰恰是一個空間還是可以更多/更少/沒有空間?等這些答案將改變最好的解決方案。 – kaylum