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?
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.
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!
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.
Look at this and use:
ss >> std::ws;
getline(ss, question);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With