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