在 C++ 中的一行中插入多个输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7945082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:45:52  来源:igfitidea点击:

Insert multiple inputs on one line in C++

c++inputiostream

提问by mmimaa

I'm trying to insert multiple inputs on one line, with comma and a space between the inputs. The method I've been using so far separates inputs with spaces.

我试图在一行上插入多个输入,输入之间用逗号和空格。到目前为止,我一直在使用的方法将输入与空格分开。

int a, b , c ,d
cin >> a >> b >> c >> d ;

With this method , the input line looks like this :

使用此方法,输入行如下所示:

1 2 3 4

But I want to be able to input data like this:

但我希望能够输入这样的数据:

1, 2, 3, 4

回答by Kerrek SB

The delimiter character for >>isn't modifiable, but you can use it in combination with ignore:

for 的分隔符>>不可修改,但您可以将其与 结合使用ignore

std::cin >> a;
std::cin.ignore(1, ',')

// rinse and repeat

回答by Nawaz

You can do this:

你可以这样做:

int main() {
        int a,b,c,d;
        char comma;
        std::cin >> a >> comma >> b >> comma >> c >> comma >> d;
        std::cout << a << " " << b << " " << c << " " << d << std::endl;
        return 0;
}

Input:

输入:

1, 2, 3, 4

Output:

输出:

1 2 3 4

Demo : http://www.ideone.com/tXQZd

演示:http: //www.ideone.com/tXQZd

回答by Bruno Alano

In C / C++, you only need do this:

在 C/C++ 中,你只需要这样做:

scanf("%d, %d, %d, %d", &a, &b, &c, &d);

You only need include the <cstdio>

你只需要包括 <cstdio>