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.
非常自我解释。我要撤消最后一个“&gt;&gt;”并使用它,好像它永远不会发生。
上下文:我正在检查关键字,但如果它不是关键字,我应该继续将其作为数据收集,因为它是一个数组数据,并且行之间可以有注释。
编辑:
经过多次尝试和错误后,我得到了这个工作:
szBuffer.seekg((int)szBuffer.tellg() - (int)szKeyWord.length());
对我来说不要太优雅,但看起来它的工作正常。
答案 0 :(得分:0)
尝试这样的事情:
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;
}
输出如下:
位置27,计数3:foo
流中剩下的内容:您好,我的名字是Bob1234 68foo87p