我已经写了一个快速的解析器,这读取一个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