简体   繁体   English

C如何读取逗号分隔的输入

[英]C how to read input separated by commas

I want to read the following input into scanf: 我想在scanf中读取以下输入:

10 0 y
2
2, 80, 40, 0

This should be ready by scanf from a separate file. 这应该由scanf从单独的文件准备好。

I can get the first two lines without the commas by just doing the following: 我只需执行以下操作即可获得没有逗号的前两行:

scanf("%d %d %c %d", a1, a2, a3, c1, a4);

How would I be able to read the third line that is separated by commas and store those in my variables? 我怎么能读取用逗号分隔的第三行并将它们存储在我的变量中?

You can just include the commas in a scanf format string: 您可以在scanf格式字符串中包含逗号:

int blinky, pinky, inky, clyde;
scanf("%d, %d, %d, %d", &blinky, &pinky, &inky, &clyde);

Here's a complete example based on your question: 以下是基于您的问题的完整示例:

#include <stdio.h>

int main(void)
{
    int a1, a2, a4;
    int blinky, pinky, inky, clyde;
    char c3;

    scanf("%d %d %c %d %d, %d, %d, %d", &a1, &a2, &c3, &a4, &blinky, &pinky, &inky, &clyde);
    printf("%d %d %c\n%d\n%d, %d, %d, %d\n", a1, a2, c3, a4, blinky, pinky, inky, clyde);

    return 0;
}

And to build and test: 并建立和测试:

$ cat input 
10 0 y
2
2, 80, 40, 0
$ make example
cc     example.c   -o example
$ ./example < input
10 0 y
2
2, 80, 40, 0

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

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