istringstream in C++

笑着哭i 提交于 2020-01-02 20:44:38

问题


I'm sure I'm just doing something stupid here, but I can't quite figure out what it is. When I try to run this code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main(int argc, char *argv[])
{
 string s("hello");

 istringstream input(s, istringstream::in);

 string s2;
 input >> s2;

 cout << s;
}

I get this error:

malloc: *** error for object 0x100016200: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

The only thing I can think of is that I allocated s2 on the stack, but I thought strings manage their own content on the heap. Any help here would be appreciated.

Thanks,

helixed

EDIT: Fixed the last line of main, where cout << s should have been cout << s2. It runs without error if I initialized s2 to "hi", but not otherwise. Is this just a weird gcc compilation problem?


回答1:


Works for me.

But I have never done this:

istringstream input(s, istringstream::in); 

Try

istringstream input(s); 



回答2:


So the answer turned out to be a bug in Xcode. Here's a similar problem and its solution.



来源:https://stackoverflow.com/questions/2633092/istringstream-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!