【发布时间】: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 保证不会对数据进行修改(就像复制它保证不会修改一样)。