将stringstream解析为字符串和双精度对象
Parse a stringstream into strings and doubles
我正在编写一个程序,它在一行上接受如下输入:
运行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!
}
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何调用返回双精度或字符串并将其保存在地图上但作为对象的类的方法
- 视觉对象 返回 C++ 中的双精度值
- C++插入到地图<双精度、多地图<整数、对象*>>
- C++将包含对象的向量转换为包含双精度的向量
- 将stringstream解析为字符串和双精度对象
- 堆上的双精度对象总是8字节对齐
- 解释c++中非规范化双精度对象的输出
- 将长双精度对象存储在多个双精度变量中
- 从双精度对象创建std::chrono::high_resolution_clock::time_point
- 从文件中读取双精度对象对(c++)
- 在c++中从双精度对象中检索分数部分