我如何从 C 文件中读取多行数据,其中每行都有分隔符来分隔该行上的不同数据?
例如,我有一个包含以下文本的文件:
Some Text | More Text | 1:23
Text Again | Even More Text | 4:56
etc...
这是我尝试过的方法,但到目前为止它对我不起作用:
char str1[20];
char str2[20];
int mins;
int secs;
char line[50];
while (fgets(line, 50, textFile) != 0) {
sscanf(line, "%20[ | ]%20[ | ]%d[:]%d", str1, str2, &mins, &secs)
}
您可能会从我的代码中猜出我是 C 语言的新手,感谢您的帮助。
最佳答案
替换
sscanf(line, "%20[ | ]%20[ | ]%d[:]%d", str1, str2, &mins, &secs)
与
sscanf(line, "%19[^|] | %19[^|] | %d:%d", str1, str2, &mins, &secs);
trim_end(str1);//remove the trailing white spaces
trim_end(str2);
#include <string.h>
#include <ctype.h>
void trim_end(char *s){
size_t len = strlen(s);
while(len--){
if(isspace(s[len]))
s[len] = 0;
else
break;
}
}
关于c - 在 C 中读取多行带有空格和定界符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495770/