C++:如何输入用逗号(,)分隔的值

C++: how to input values separated by comma(,)

本文关键字:分隔 何输入 输入 C++      更新时间:2023-10-16
int a, b, c, d;

共有4个变量。

我希望用户输入4个值,每个值用逗号(,)分隔

就像这样:

stdin:

1,2,3,4

以下代码在C 中工作

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

但是我应该如何用C++进行编码呢?

我对这里的错误评论感到有点惊讶[1]

你可以走两条基本路线:

  • 使用操纵器样式的对象处理分隔符,或者
  • 在流中注入一个特殊的方面,该方面需要空格来包含逗号

我将专注于第一个;在共享流中注入奇怪的行为通常是个坏主意,即使是暂时的("共享"是指代码的其他部分也可以访问它;本地字符串流是注入专门行为的理想候选者)。

"下一项必须是逗号"提取器:

#include <cctype>
#include <iostream>
struct extract
{
char c;
extract( char c ): c(c) { }
};
std::istream& operator >> ( std::istream& ins, extract e )
{
// Skip leading whitespace IFF user is not asking to extract a whitespace character
if (!std::isspace( e.c )) ins >> std::ws;
// Attempt to get the specific character
if (ins.peek() == e.c) ins.get();
// Failure works as always
else ins.setstate( std::ios::failbit );
return ins;
}
int main()
{
int a, b;
std::cin >> a >> extract(',') >> b;
if (std::cin)
std::cout << a << ',' << b << "n";
else
std::cout << "quiznak.n";
}

运行此代码时,只有当下一个非空白项是逗号时,extract操纵器/提取器/athing才会成功。否则会失败。

你可以很容易地修改它,使逗号可选:

std::istream& operator >> ( std::istream& ins, optional_extract e )
{
// Skip leading whitespace IFF user is not asking to extract a whitespace character
if (!std::isspace( e.c )) ins >> std::ws;
// Attempt to get the specific character
if (ins.peek() == e.c) ins.get();
// There is no failure!
return ins;
}
...
std::cin >> a >> optional_extract(',') >> b;

等等。

[1]cin >> a >> b;而不是等价于CCD_ 3。C++不会神奇地忽略逗号。就像在C中一样,您必须明确地对待它们。

对于使用CCD_ 4和CCD_;虽然组合是有效的,但实际问题只是从std::cin转移到另一个流对象,仍然需要处理。