Skip whitespaces with getline

喜你入骨 提交于 2020-12-28 07:50:28

问题


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?


回答1:


Look at this and use:

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



回答2:


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.



来源:https://stackoverflow.com/questions/20045726/skip-whitespaces-with-getline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!