Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip whitespaces with getline

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?

like image 976
JNevens Avatar asked Nov 18 '13 10:11

JNevens


People also ask

Does Stringstream ignore whitespace?

Does stringstream ignoring whitespaces? Technically the operator>>() function ignores leading whitespace. Doing ss. ignore(1) is a way to do it manually, but it's unnecessary.

How do I use Getline with delimiter?

Using std::getline() in C++ to split the input using delimiters. We can also use the delim argument to make the getline function split the input in terms of a delimiter character. By default, the delimiter is \n (newline). We can change this to make getline() split the input based on other characters too!

Should I use getline or cin?

The main difference between getline and cin is that getline is a standard library function in the string header file while cin is an instance of istream class. In breif, getline is a function while cin is an object. Usually, the common practice is to use cin instead of getline.


Video Answer


2 Answers

Look at this and use:

ss >> std::ws;
getline(ss, question);
like image 128
Axel Avatar answered Oct 02 '22 04:10

Axel


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.

like image 39
john Avatar answered Oct 03 '22 04:10

john