gpt4 book ai didi

c++ - 如何在字符串流中重新插入字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 14:14:44 25 4
gpt4 key购买 nike

std::string szKeyWord;
...
std::stringstream szBuffer(szLine);
szBuffer>>szKeyWord;
...
szBuffer<<szKeyWord;
szBuffer>>myIntVar; // will NOT format keyword here, will act as the line above never happened.

几乎不言自明。我想撤消最后一个“>>”并像从未发生过一样使用它。

上下文:我正在检查关键字,但如果它不是关键字,我应该继续收集它作为数据,因为它是一个数组数据,并且行与行之间可以有注释。

编辑:

经过大量尝试和错误后,我让它工作了:

szBuffer.seekg((int)szBuffer.tellg() - (int)szKeyWord.length());

在我看来并不优雅,但看起来工作正常。

最佳答案

尝试这样的事情:

using namespace std;

string PeekString(stringstream& ss, int position = 0, char delim = '\n', int count = 0)
{
string returnStr = "";
int originalPos = (position > 0) ? position : ss.tellg();
if (originalPos == position) ss.seekg(position);
int pos = originalPos;
int i = 0, end = (count < 1) ? ss.str().length() : count;
char c = ss.peek();

while (c != delim && !ss.eof() && i != end)
{
returnStr += c;
pos++;
i++;
ss.seekg(pos);
c = ss.peek();
}
ss.seekg(0);
return returnStr;
}

用法是这样的:

int main()
{
string s = "Hello my name is Bob1234 68foo87p\n";
stringstream ss;
ss << s;
cout << "Position 0, delim \'\\n\': " << PeekString(ss) << endl;
cout << "Position 0, delim \' \': " << PeekString(ss,0,' ') << endl;
cout << "Position 17, delim \' \': " << PeekString(ss,17,' ') << endl;
cout << "Position 25, delim \'\\n\': " << PeekString(ss, 25) << endl;
cout << "Position 27, count 3: " << PeekString(ss, 27, '\n', 3) << endl << endl;

string newstring;
char temp[100];
ss.getline(temp, 100);
newstring = temp;

cout << "What's left in the stream: " << newstring;

cin.get();
return 0;
}

输出看起来像这样:

  • 位置 0,delim '\n':你好我的名字是 Bob1234 68foo87p
  • 位置 0,delim ' ':你好
  • 位置 17,delim ' ':Bob1234
  • 位置 25,delim '\n': 68foo87p
  • 位置 27,计数 3:foo

  • 流中剩下的内容:你好,我的名字是 Bob1234 68foo87p

关于c++ - 如何在字符串流中重新插入字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12251246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com