How can I read in multiple lines of data from a file in C, where each line has delimiters to separate different pieces of data on that line?
如何从C中的文件中读取多行数据,其中每行都有分隔符以分隔该行上的不同数据?
For example, I have a file with the following text:
例如,我有一个包含以下文本的文件:
Some Text | More Text | 1:23
Text Again | Even More Text | 4:56
etc...
This is what I have tried, but it has not worked for me so far:
这是我尝试过的,但到目前为止它对我没用:
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)
}
You can probably guess I'm new to C from my code, I appreciate any help.
您可以从我的代码中猜测我是C的新手,我感谢任何帮助。
1 个解决方案
#1
5
replace
sscanf(line, "%20[ | ]%20[ | ]%d[:]%d", str1, str2, &mins, &secs)
with
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;
}
}
#1
5
replace
sscanf(line, "%20[ | ]%20[ | ]%d[:]%d", str1, str2, &mins, &secs)
with
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;
}
}