这个C输入的C ++等价物是什么?

时间:2015-03-18 04:40:59

标签: c++

我如何在C ++中实现这一行

scanf("%lf, %lf, %lf", &a, &b, &c)

ie:我想获取以逗号分隔的文件数据输入

3 个答案:

答案 0 :(得分:2)

解决方案1:

std::cin >> a;
std::cin.ignore();
std::cin >> b;
std::cin.ignore();
std::cin >> c;

ignore()忽略单个字符。

解决方案2:

为逗号使用虚拟变量:

char comma;
std::cin >> a >> comma >> b >> comma >> c;

答案 1 :(得分:0)

char comma1, comma2;
if (file_stream >> a >> comma1 >> b >> comma2 >> c &&
    comma1 == ',' && comma2 == ',')
    ...a b and c read & parsed successfully...
else
    ...error...

Remy Lebeau在下面评论说他认为下面的功能相同的代码更容易让初学者理解 - 我不同意但是读者可以自己决定:

char comma1, comma2;
file_stream >> a >> comma1 >> b >> comma2 >> c;
if (!file_stream.fail() && (comma1 == ',') && (comma2 == ','))
    ...a b and c read & parsed successfully...
else
    ...error...

如果您的“文件数据”按照您在评论中指出的stdin到达,则可以将上面的file_stream替换为std::cin。如果要使用实际文件流:

if (std::ifstream file_stream(filename))
    if (file_stream >> a >> ...as above...

或者,this old answerStr类进行编码,允许这样使用:

if (file_stream >> a >> Str(",") >> b >> Str(",") >> c)
    ...a b and c read & parsed succesfully...

答案 2 :(得分:-2)

您想要从文件而不是标准流中读取数据吗? 然后使用fscanf