我想读取一个字符串并在C ++中解析它以将其从命令行转换为双精度数 并在向量中获取每个数字
'1.1,2.3,3.4,4.6,5.8,6.9,7.8,8.0,9.9,10.11,11.67'
std::string tempInput;
tempInput = argv[1];
vector <double> example;
std::vector< std::string > tokens;
while ( std::cin >> tempInput ) {
example.push_back( <double>( tempInput ) );
}
那么最简单的方法是什么/
答案 0 :(得分:3)
用空格替换所有逗号:
std::string input = "1.1,2.3,3.4,4.6,5.8,6.9,7.8,8.0,9.9,10.11,11.67";
std::replace(input.begin(), input.end(), ',', ' ');
std::vector<double> result;
std::istringstream inputStream(input);
double value;
while (inputStream >> value)
result.push_back(value);
inputStream >> std::ws;
if (!inputStream.eof())
// Handle input error
或者,考虑while
:
std::istream_iterator
循环
std::vector<double> result;
std::istringstream inputStream(input);
std::copy(std::istream_iterator<double>(inputStream),
std::istream_iterator<double>(),
std::back_inserter(result));