简体   繁体   English

时间:2019-05-16 标签:c++stringstreaminvalidatedstringpointer

[英]c++ stringstream invalidated string pointer

I have an stringstream , pushing to it in an iteration.我有一个stringstream ,在迭代中推送到它。 After casting its content to an int object, it never changes after that.将其内容转换为int对象后,它永远不会更改。 I think it changes but instance.str() is pointing to an invalidated place in which the string is not there anymore.我认为它发生了变化,但instance.str()指向一个无效的地方,其中字符串不再存在。

bool h = 1;
stringstream ss;
for(int i = 0; i < input.length(); i++)
{
    if(input[i] != ':')
    {
        cout << "input:  " << input[i] << endl;
        ss << input[i];
        cout << "ss:  " << ss.str() << endl;
    }
    else
        if(h)
        {
            ss >> hour;
            ss.str(string());
            h = 0;
        }   
}

in this loop, after the satisfaction of the condition( h being true ), the stream's content is casting to an int .在此循环中,在满足条件( htrue )后,流的内容将转换为int till this moment everything works fine but after this moment, ss.str() returns an empty string .直到这一刻一切正常,但在这一刻之后, ss.str()返回一个空string

was my guess about invalidated string pointer right?我对无效字符串指针的猜测是否正确? if yes, what is the reason?如果是,原因是什么? if no, what is the reason of this behavior?如果不是,这种行为的原因是什么?

UPDATE: I changed the sources code because the previous version was the way I handled the issue by this trick:更新:我更改了源代码,因为以前的版本是我通过这个技巧处理问题的方式:

stringstream a(ss.str());
a >> hour;
ss.str(string());

The problem is that this line:问题是这一行:

ss >> hour;

sets the eof bit of your stream because you reached the end of the string.设置流的 eof 位,因为您到达了字符串的末尾。 When the eof bit is set, then the stream does not work any more.当设置 eof 位时,流将不再工作。 So you have to clear it after setting the empty string:所以你必须在设置空字符串后清除它:

ss.str(string())
ss.clear()

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

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