【问题标题】:I filed my vector from a text file and it wont cout as one line. How can I do this?我从文本文件中归档了我的向量,它不会算作一行。我怎样才能做到这一点?
【发布时间】:2016-03-25 01:40:45
【问题描述】:

长话短说,我需要将向量作为单行进行计算,而无需创建自己的新行以使我的程序正常工作。我读入向量的文本文件是

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

如果我手动输入单词并将它们添加到我的数据结构中,我的程序可以工作,但是如果从通过文本文件填充的向量中添加,则一半的程序不起作用。在有人说要求更好地描述问题之前,我只需要知道如何填充向量,以便它将作为单行输出。

【问题讨论】:

    标签: c++ vector io


    【解决方案1】:

    您的代码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);
    

    ...或者(正如 Barry 在 cmets 中建议的那样)...

    while (getline(myFile, line))
    {
        std::istringstream iss(line);
        std::string field;
        while (getline(iss, field, '#'))
            ...
    }
    

    【讨论】:

    • @BarryTheHatchet: 是的 - 无论如何通常都是可取的,因此您可以计算诊断消息的行号......
    • @BarryTheHatchet 那么我怎样才能将笔记本电脑#a 适合放在膝上的小型计算机变成 string1 = 笔记本电脑和 string2 = 适合放在膝上的小型计算机。您发布的两条建议均无效。
    • @ThePeskyWabbit 你是什么意思“没有工作” - 发生了什么? FWIW,如果您收到有关 andnot 的错误消息,这意味着您没有使用符合 C++ 标准的编译器(也许您正在使用微软的抱歉的借口?):如果是这样,您可以使用 &amp;&amp;! 分别代替,或者在 MS 文档中搜索命令行选项以启用 andnot
    • 我确实使用了 && 和 !因为这确实是VS2012
    • @ThePeskyWabbit:你不是一个容易提供帮助的 Wabbit ;-P; 您使用这些之后,它是否开始工作,或者您是说即使使用这些也不起作用?如果是后者,究竟发生了什么?编译错误(如果是这样)?错误的输出(如果是,输出是什么)? ...
    【解决方案2】:
    while(getline(myFile, line, '#'))
    

    在这里,您告诉std::getline 使用“#”字符而不是换行符'\n' 作为分隔符。

    所以,这仅仅意味着std::getline 将不再认为'\n' 有什么特别之处。这只是std::getline() 将继续阅读的另一个字符,寻找下一个#

    因此,您最终会将换行符读入各个字符串,然后将它们作为您打印的字符串的一部分输出到 std::cout

    【讨论】:

      猜你喜欢
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多