我有一个这样的文本文件:
代码主题名称等
其中code和ects是整数,而subject_name是一个字符串,可以是多个单词长,有时还包含数字。
我尝试过fscanf(f, "%d %s %d", &code, subject_name, &ects);
,该操作不起作用,因为字符串中有空格。
"%d %[^\n] %d"
也将不起作用,因为字符串会吞下ects。
正确的方法是什么?
步骤1:读取行
#define LINE_MAX_EXPECTED_SIZE 100
char buf[LINE_MAX_EXPECTED_SIZE + 2];// Let code read lines that are too long
if (fgets(buf, sizeof buf, f)) {
buf[strcspn(buf, "\n\r")] = '\0'; // lop off potential end-of-line
if (strlen(buf) >= LINE_MAX_EXPECTED_SIZE || buf[0] == '\0') {
fprintf(stderr, "Line too long/short. <%s>\n", buf);
exit(EXIT_FAILURE);
}
...
确定,现在我们已读取line并另存为string。
步骤2:由于subject_name
和ects
可以是数字,所以让代码先查找ects
,因为它是一个且只有一个数字。
// Start at end
char *end = strlen(buf) - 1;
if (!isdigit((unsigned char) *end)) {
fprintf(stderr, "No number at end. <%s>\n", buf);
exit(EXIT_FAILURE);
}
while (end > buf && isdigit((unsigned char) * --end)) {
;
}
if (end > buf && (*end == '-' || *end == '+')) {
end--;
}
ects = atoi(end + 1); // or better strtol()
end[1] = '\0'; // lop off ects
现在buf
希望可以用用户代码code
,subject_name
等进行解析的sscanf()
和strtol()
。将其留给OP。