简体   繁体   English

如何在stringstream上重新插入字符串?

[英]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.

Pretty much self explanatory. 几乎可以自我解释。 I want to undo the last ">>" and use it as if it never happens. 我想撤消最后一个“ >>”并使用它,好像它永远不会发生一样。

Context: Im checking for keywords, but if its not a keyword, I should keep collecting it as data, because its an array data, and there can be comment between lines. 上下文:我正在检查关键字,但是如果不是关键字,我应该继续将其作为数据收集,因为它是数组数据,并且行之间可能会有注释。

EDIT: 编辑:

After a LOT of try and error, I get this to work: 经过大量的尝试和错误后,我得到了这个工作:

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

Dont look elegant to me, but looks like its working fine. 对我来说看起来并不优雅,但看起来工作正常。

Try something like this: 尝试这样的事情:

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;
}

The usage would be like this: 用法如下:

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;
}

The output looks like this: 输出看起来像这样:

  • Position 0, delim '\\n': Hello my name is Bob1234 68foo87p 位置0,delim'\\ n':您好,我叫Bob1234 68foo87p
  • Position 0, delim ' ': Hello 位置0,delim'':您好
  • Position 17, delim ' ': Bob1234 位置17,delim'':Bob1234
  • Position 25, delim '\\n': 68foo87p 位置25,delim'\\ n':68foo87p
  • Position 27, count 3: foo 位置27,计数3:foo

  • What's left in the stream: Hello my name is Bob1234 68foo87p 流中还剩下什么:您好,我叫Bob1234 68foo87p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM