我把矢量从一个文本文件中归档,它不会变成一行.我该怎么做

I filed my vector from a text file and it wont cout as one line. How can I do this?

本文关键字:我该怎么做 一行 文件 一个 文本      更新时间:2023-10-16

长话短说,我需要我的向量作为一行进行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,作为打印字符串的一部分。