Skip whitespaces with getline

JNevens picture JNevens · Nov 18, 2013 · Viewed 35.6k times · Source

I'm making a program to make question forms. The questions are saved to a file, and I want to read them and store them in memory (I use a vector for this). My questions have the form:

1 TEXT What is your name?
2 CHOICE Are you ready for these questions?
Yes
No

My problem is, when I'm reading these questions from the file, I read a line, using getline, then I turn it into a stringstream, read the number and type of question, and then use getline again, on the stringstream this time, to read the rest of the question. But what this does is, it also reads a whitespace that's in front of the question and when I save the questions to the file again and run the program again, there are 2 whitespaces in front of the questions and after that there are 3 whitespaces and so on...

Here's a piece of my code:

getline(file, line);
std::stringstream ss(line);
int nmbr;
std::string type;
ss >> nmbr >> type;
if (type == "TEXT") {
    std::string question;
    getline(ss, question);
    Question q(type, question);
    memory.add(q);

Any ideas on how to solve this? Can getline ignore whitespaces?

Answer

Axel picture Axel · Nov 18, 2013

Look at this and use:

ss >> std::ws;
getline(ss, question);