C++ 使用 getline 跳过空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20045726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:52:59  来源:igfitidea点击:

Skip whitespaces with getline

c++stringwhitespacegetlinestringstream

提问by JNevens

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...

我的问题是,当我从文件中读取这些问题时,我使用 getline 读取一行,然后将其转换为字符串流,读取问题的数量和类型,然后再次使用 getline,这次是在字符串流上, 阅读问题的其余部分。但是这样做的作用是,它还会读取问题前面的空格,当我再次将问题保存到文件并再次运行程序时,问题前面有 2 个空格,之后有 3 个空格和很快...

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?

关于如何解决这个问题的任何想法?getline 可以忽略空格吗?

回答by Axel

Look at thisand use:

看看这个并使用:

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

回答by john

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

没有 getline 不会忽略空格。但是没有什么可以阻止您在使用 getline 之前添加一些代码来跳过空格。例如

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

Soemthing like that anyway.

反正就是这样。