Skip whitespaces with getline
Asked Answered
L

2

8

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?

Luxor answered 18/11, 2013 at 10:41 Comment(2)
So.. erase the leading whitespace before sending it to Question (which apparently has a nested class called Question.. interesting).Durante
@Durante Oops, mistake I made.. Fixing it now!Luxor
R
31

Look at this and use:

ss >> std::ws;
getline(ss, question);
Retraction answered 18/11, 2013 at 10:45 Comment(0)
T
5

No getline doesn't ignore whitespaces. But there nothing to stop you adding some code to skip whitespaces before you use getline. For instance

    while (ss.peek() == ' ') // skip spaces
        ss.get();
    getline(ss, question);

Soemthing like that anyway.

Telefilm answered 18/11, 2013 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.