0

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/

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.