1
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.

4

1 回答 1

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

输出如下所示:

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

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

于 2012-12-14T12:19:20.950 回答