繁体   English   中英

在C中读取多行带有空格和定界符的字符串

[英]Reading multiple lines of strings with spaces and delimiters in C

如何从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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM