[英]How to reinsert string on the stringstream?
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;
}
輸出看起來像這樣:
位置27,計數3:foo
流中還剩下什么:您好,我叫Bob1234 68foo87p
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.