2

I have a vector of strings that contain numbers, words, spaces, and even weird characters like quotation marks. I am trying to read it all in using a stringstream so I can separate the doubles from strings.

When I do this:

stringstream contains

4165 This package contains 12 1/2" Screws

Code:

stringstream >> mydouble 
stringstream >> mystring

mydouble contains

4165

Then the only thing that gets read into mystring is

This package contains 12 1/2

How can I let it keep the entire line?

Sometimes my file contains this:

4165 This package contains 2 1/2" Screws

65 This package contains 12> 1/2" Screws

This package contains 1 screw

1
  • 1
    What is mystring's type? The way you have it, if that's a std::string or a char array, the only thing in there should be "This". Commented Jun 1, 2012 at 4:53

1 Answer 1

3

Regrettably, the stream extraction operator >> is not good at the kind of thing you wish it to do. The right way to do what you want is to fetch the whole line by

std::getline(stringstream, myline);

then to write code to parse the line.

How to parse the line? Five options come to mind:

  1. Write your own code to do it without relying on special tools.
  2. Use Lex/Flex and Yacc/Bison.
  3. Use Boost Spirit.
  4. Use POSIX <regex.h>.
  5. Use C++11 <regex> or TR1 <tr1/regex>.

None of these however is entirely trivial. If you want to know, for your application, I'd probably go with choice 1, choice 3 or choice 5. Whatever you choose to do, good luck to you.

If you don't know where to start, why don't you look up std::getline(), presented in <string>, and std::atoi(), presented in <cstdlib>? These should afford you some ideas as to where to go next.

Sign up to request clarification or add additional context in comments.

1 Comment

Correction: An earlier version of the answer referred to std::getline() as presented in <iostream>. That was the wrong header. There are two, distinct std::getline() functions in the standard library, and you want the other one, the one presented in <string>. I have corrected the answer above accordingly.

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.