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

标签 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;
    }
}

关于c - 在 C 中读取多行带有空格和定界符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495770/

相关文章:

c++ - 科学程序员的阅读 list

c - Pthread 的奇怪行为

c - malloc 如何获取比分配更多的数据字节数

c - 将套接字绑定(bind)到网络接口(interface)

c - while 测试条件时使用 scanf 内部

c++ - 使用 libnl-3-route "Invalid input data or parameter"添加路由

c - 指针类型转换如何在 C 中工作

c - 并行化一个函数

c - 如何在不强制使用 c 的情况下为每个线程分配任务,即每个线程在完成第一项工作后需要执行一些工作?

c - 使用 GLib 集合删除列表中的重复项