使用getline跳过空格

JNe*_*ens 5 c++ string whitespace stringstream getline

我正在制作一个程序来制作问题表格.问题保存到文件中,我想读取它们并将它们存储在内存中(我使用了一个向量).我的问题有以下形式:

1 TEXT What is your name?
2 CHOICE Are you ready for these questions?
Yes
No
Run Code Online (Sandbox Code Playgroud)

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

这是我的一段代码:

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);
Run Code Online (Sandbox Code Playgroud)

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

Axe*_*xel 21

看看这个并使用:

ss >> std::ws;
getline(ss, question);
Run Code Online (Sandbox Code Playgroud)


joh*_*ohn 5

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

    while (ss.peek() == ' ') // skip spaces
        ss.get();
    getline(ss, question);
Run Code Online (Sandbox Code Playgroud)

无论如何,这样的东西.