用getline跳过空格 [英] Skip whitespaces with getline

查看:209
本文介绍了用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

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

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(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);

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

Any ideas on how to solve this? Can getline ignore whitespaces?

推荐答案

查看并使用:

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

这篇关于用getline跳过空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆