简体   繁体   English

如何在 C89 中读取字符串直到逗号?

[英]How do I read a string until a comma in C89?

I am trying to read a CSV file in c89 using scanf :我正在尝试使用scanf读取c89中的 CSV 文件:

FOO,2,3
BAR,5,4
...

This is what I have tried:这是我尝试过的:

#include <stdio.h>

int main() {

    char code[10];
    double a,b;

    while( scanf("%s,%lf,%lf", code, &a, &b)!=EOF ) {
        printf("> %s\n", code);
        printf("> %s,%lf,%lf\n", code, a, b);
    }

    return 0;
}

This is the output I get:这是我得到的 output:

$ ./a.out
A,2,3
> A,2,3
> A,2,3,0.000000,0.000000
B,5,4
> B,5,4
> B,5,4,0.000000,0.000000
$ 

This is the output I was expecting from the above code:这是我从上面的代码中期待的 output:

$ ./a.out
A,2,3
> A
> A,2.000000,3.000000
B,5,4
> B
> B,5.000000,4.000000
$ 

Edit编辑

As per the comment provided I have tried:根据提供的评论,我尝试过:

#include <stdio.h>

int main() {

    char code[10];
    double a,b;

    while( scanf("%9[^,],%lf,%lf", code, &a, &b)!=EOF ) {
        printf("> %s\n", code);
        printf("> %s,%lf,%lf\n", code, a, b);
    }

    return 0;
}

And I get:我得到:

$ cat > test.txt
A,2,3
B,4,5
C,5,6
$ cat test.txt | ./a.out 
> A
> A,2.000000,3.000000
> 
B
> 
B,4.000000,5.000000
> 
C
> 
C,5.000000,6.000000
> 

> 
,5.000000,6.000000
$

Apparently the first record is properly processed but not the subsequent ones.显然,第一条记录已正确处理,但后续记录未正确处理。

Also I have the question about what the 9 does and if the whole %9[^,] is part of c89 .我也有关于9做什么以及整个%9[^,]是否是c89的一部分的问题。

I found a workaround that is reaching each line into a buffer and replacing the commas by spaces first, then I apply the %s .我找到了一种解决方法,将每一行放入缓冲区并首先用空格替换逗号,然后应用%s

#include <stdio.h>

int main() {

    char line[256];    
    char code[10];
    double a,b;

    while(scanf("%s", line) != EOF) {

        /* REPLACE ALL , BY SPACES TO SIMPLIFY SCANF USAGE */
        char *p = line;
        while(*p!='\0') {
            if(*p==',') {
                *p = ' ';
            }
            p++;
        }


        sscanf(line,"%s %lf %lf", code, &a, &b);
        printf("> %s\n", code);
        printf("> %s,%lf,%lf\n", code, a, b);               
    }    

    return 0;   

}

Not sure if it is the most elegant solution, but improves readability of the scanf part.不确定它是否是最优雅的解决方案,但提高了 scanf 部分的可读性。

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

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