[英]Read string as command line argument C++
I want to read a string and parse it in C++ to convert it to doubles from command line and get each number in a vector 我想读取一个字符串并在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 ) );
}
So what would be the easiest way of doing this/ 因此,最简单的方法是这样做/
Replace all of the commas with spaces: 用空格替换所有逗号:
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
Or, instead of the while
loop, consider std::istream_iterator
: 或者,而不是
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.