C++:如何输入用逗号(,)分隔的值
C++: how to input values separated by comma(,)
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
转移到另一个流对象,仍然需要处理。
相关文章:
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- C++逗号分隔的输入数组代码过早退出
- 获取带有字符 X 的输入 X/X/etc 并用斜杠 / 分隔它
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 如果用户输入两个或多个由空格分隔的字符串C++如何防止缓冲区溢出?
- 使用运算符将分隔的输入分隔>>变量
- 来自 2 个不同向量的输入,用逗号分隔
- 如何将输入重定向与特殊整数作为分隔线和直至EOF
- 按标记分隔输入
- 如何在用空格分隔的行中获得无限的输入
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 如何使用符号分隔字符串而不是空格的输入字符串流
- 以C++分隔用户输入的时间
- 将空格分隔的输入读取到C++中的数组中
- 读取用空格分隔的输入数字并保存到数组中
- 如何从命令行中读取以空格分隔的输入数字
- 在C++中按空格分隔用户输入有什么更好的解决方案?
- 读取与文件分隔的输入空间
- 读取以制表符分隔的输入并跳过空白字段
- 读取由空格或换行符分隔的输入.