【问题标题】:How to ignore \n for istream strings如何忽略 istream 字符串的 \n
【发布时间】:2013-06-05 12:39:54
【问题描述】:

有没有人对我如何忽略来自 istream 的“\n”有任何建议?我正在尝试从 txt 文件中提取数据,其中某些“单元格”中的文本已写入,因此当用户按下 Enter 时会出现“\n”。

我的目标是获取此文本的某些部分并用“ ; ”分隔这些部分。但是,这样做时,有时会吸入一个“\n”,并且输出单元格开始向下继续,而不仅仅是从右到左的行(这是首选)。

任何建议将不胜感激!

string vectorToString(vector<size_t> positionVector, string mainString,
                                      string outputString, int numLetters)

{
    //Check how many different positions were found and make that the length
    //of the vector that will store all the strings for each finding
    int positionVectorLength = positionVector.size();
    //foundPos is the position of the cursor along the foundPositions vector
    int vectorPosition=0;
    while (vectorPosition < positionVectorLength)
    {
        //define local variable that will store the value along the vector
        size_t vectorPositionValue = positionVector.at(vectorPosition);


        //append the numLetters after the positionValue in string frameNum
        outputString.append(mainString, vectorPositionValue, numLetters);
        outputString.append(" ; ");     

        //reiterate until all the positions have been recorded
        vectorPosition+=1;
    }

    //return the string of frame numbers
    return(outputString);
}

【问题讨论】:

  • 你应该使用 const & 和 & 作为你的函数参数。您不能使用 string::find 和 string::erase 删除输入字符串中所有出现的 '\n' 吗?
  • @UldisK 你为什么这么说?
  • 您提到用户输入 enter 并且这被吸入了。也许它就像使用 istream::getline() 一样简单? cplusplus.com/reference/istream/istream/getline 它的默认分隔符是 '\n' 并丢弃它。
  • 您正在复制未修改的大型集合值..您应该将它们作为“const &”传递..
  • 补充 UldisK 所说的内容。您正在按值传递“positionVector”变量,这意味着您每次调用此函数时都会复制整个向量。这是很多开销。如果您通过 const& 传递,您将通过引用传递(保存副本)并且 const 保证不会对数据进行修改(就像复制它保证不会修改一样)。

标签: c++ string output istream


【解决方案1】:

您可以使用它从字符串中删除所有\n:

mainString.erase(std::remove(mainString.begin(),mainString.end(),'\n'),mainString.end());

【讨论】:

  • 但最好不要一开始就拥有它们。
  • 是的,但是“我正在尝试从 txt 文件中提取数据”,它们已经存在,所以在某一时刻 OP 将不得不删除它们。不过,我同意,不阅读它们会更好。
  • 不,许多从文件中读取的方法都会跳过换行符。 :)
  • 我没有说你不能,我只是提供了一种从字符串中删除字符的方法,以防他/她无法更改文件的读取方式。
  • 无需防御;我只是说。
猜你喜欢
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多