Reputation: 25058
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
'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/
Upvotes: 0
Views: 761
Reputation: 355387
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
:
std::vector<double> result;
std::istringstream inputStream(input);
std::copy(std::istream_iterator<double>(inputStream),
std::istream_iterator<double>(),
std::back_inserter(result));
Upvotes: 3