将stringstream解析为字符串和双精度对象

Parse a stringstream into strings and doubles

本文关键字:双精度 对象 字符串 stringstream      更新时间:2023-10-16

我正在编写一个程序,它在一行上接受如下输入:

运行10.1 50.2

其中"Run"为字符串,其余部分为双精度类型。科学符号和负数也可以用作双输入:例如-5.88e-11(标准c++库允许这样做)。

这是我尝试的初始代码。

string command; 
double input1; 
double input2; 
getline(cin,input);
stringstream ss(input);
ss >> command >> input1 >> input2;

这种方法的问题是,如果在double的位置输入空格或字母,则stringstream的输出将为0。我相信这是因为c++中没有double的空占位符。

我尝试的另一种方法是将每个输入读取为字符串,检查字符串是否为数字并将其转换为双精度类型。然而,当可以输入科学符号和负数时,这就变得复杂了。尝试:

for (int i=0; input1[i]; i++){
    if (isdigit(input1[i])){
        isDigit = true;
    }else{
        isDigit = false;
    }
}

我如何解析这个输入与字符串和字母数字双精度在同一行?(同时保留底片和科学符号)

谢谢!

直接使用std::cin并检查在解析流时是否有错误

std::string command;
double arg1, arg2;
if (std::cin >> command >> arg1 >> arg2) {
    std::cout << command << std::endl;
    std::cout << arg1 << std::endl;
    std::cout << arg2 << std::endl;
} else {
    // error!
}