我把矢量从一个文本文件中归档,它不会变成一行.我该怎么做
I filed my vector from a text file and it wont cout as one line. How can I do this?
长话短说,我需要我的向量作为一行进行cout,而不需要创建自己的新行来使我的程序正确工作。我在矢量中读取的文本文件是
laptop#a small computer that fits on your lap#
helmet#protective gear for your head#
couch#what I am sitting on#
cigarette#smoke these for nicotine#
binary#ones and zeros#
motorcycle#two wheeled motorized bike#
oj#orange juice#
test#this is a test#
使用循环填充矢量:
if(myFile.is_open())
{
while(getline(myFile, line, '#'))
{
wordVec.push_back(line);
}
cout << "words added.n";
}
并使用以下方式打印:
for(int i = 0; i < wordVec.size(); i++)
{
cout << wordVec[i];
}
并输出如下:
laptopa small computer that fits on your lap
helmetprotective gear for your head
couchwhat I am sitting on
cigarettesmoke these for nicotine
binaryones and zeros
motorcycletwo wheeled motorized bike
ojorange juice
testthis is a test
如果我手动输入单词并将其添加到我的数据结构中,我的程序就可以工作,但如果从通过文本文件填充的向量中添加,一半的程序就无法工作。在有人要求更好地描述这个问题之前,我所需要知道的就是如何填充向量,使其输出为一行。
您的代码getline(myFile, line, '#')
会将文件末尾或下一个"#"之前的所有内容读取到line
中,其中包括任何换行符。因此,当您阅读文本文件内容时。。。
laptop#a small computer that fits on your lap#
helmet#protective gear for your head#
你也可以把它想象成…
"laptop#a small computer that fits on your lap#nhelmet#protective gear for your head#"
line
采用连续值。。。
"laptop"
"a small computer that fits on your lap"
"nhelmet"
...etc....
注意"nhelmet"
中的换行符。
有很多方法可以避免或纠正这种情况,例如…
while ((myFile >> std::skipws) and getline(myFile, line, '#'))
...
或
if (not line.empty() and line[0] == 'n')
line.erase(0, 1);
或者(正如巴里在评论中所说)。。。
while (getline(myFile, line))
{
std::istringstream iss(line);
std::string field;
while (getline(iss, field, '#'))
...
}
while(getline(myFile, line, '#'))
在这里,您告诉std::getline
使用"#"字符而不是换行符'n'
作为分隔符。
所以,这只是意味着std::getline
将不再认为'n'
有什么特别之处。这只是std::getline
()将继续读取的另一个字符,以寻找下一个#
。
因此,您最终将换行符读取到各个字符串中,然后将它们输出到std::cout
,作为打印字符串的一部分。
相关文章:
- 我该怎么做才能摆脱使用命名空间时的语法错误?
- 模板类是这里的最佳选择吗?如果是,我该怎么做?
- 在C++中,创建'n'数量的对象的推荐方法是什么,其中n是用户定义的。我该怎么做?
- 我必须输入我的名字才能输入我的资源,我该怎么做
- swig-包装到c#时,没有默认的std ::列表,我该怎么做
- C ++ 12位变量,我该怎么做?
- 在使用 emscripten 编译时,我该怎么做才能包含 <X11/Xlocale.h>?
- 我该怎么做 - 就像一个速度 的功率快速的功率一样快速的两个功率
- 错误:不允许指向不完整类类型的指针.我该怎么做
- 我该怎么做 throw 来处理 C++ 中的错误数据类型
- 正在尝试初始化区域结构内的边缘结构.我该怎么做
- 我想在我的main中为下面的代码创建一个对象..那么我该怎么做呢
- 我该怎么做才能不使用!openFile.eof()
- 这是对reinterpret_cast的合法使用吗?如果不是,我该怎么做
- 我把矢量从一个文本文件中归档,它不会变成一行.我该怎么做
- 我该怎么做才能在 eclipse 中设置C++开发
- C ++ win 32,我想将项目列表添加到组合框中.我该怎么做
- 我有一个类来表示整数,我想区分磅和公斤,我该怎么做
- 如果我只想在模板中专门研究一种方法,我该怎么做
- 我正试着计算月、日和年.我该怎么做呢?