我在网上找到了这个代码作为模板,用于执行字符串到float/int/double转换.它只在这里,所以我有一些东西可以参考这个问题....
我想有一个用户输入一个数字作为一个字符串,将其转换为float,测试它的成功和辍学,如果进入了"Q"或打印"无效的输入",如果它是不是"Q'uit性格和返回更多输入.
转换失败测试的语法是什么?它会是ss.fail()吗?
// using stringstream constructors.
#include <iostream>
#include <sstream>
using namespace std;
int main () {
int val;
stringstream ss (stringstream::in | stringstream::out);
ss << "120 42 377 6 5 2000";
/* Would I insert an
if(ss.fail())
{
// Deal with conversion error }
}
in here?! */
for (int n=0; n<6; n++)
{
ss >> val;
cout << val*2 << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)