簡體   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