Thread: "std::stringstream" unexpected behavior (simple example)

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    28

    "std::stringstream" unexpected behavior (simple example)

    hi Guys,

    i'm puzzled by the values i'm getting back from stringstream

    Code:
    #include <sstream>
    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        std::stringstream ss("1");
        int x;
        ss >> x;
        std::cout <<"(" <<x <<")";
    
        ss.str("1");
        int y;
        ss >> y;
        std::cout <<"(" <<y <<")";
    
        return 0;
    }
    output is!
    Code:
    (1)(-1)
    i was of course expecting:
    Code:
    (1)(1)
    it's causing problems in one of my programs.
    anyone got an explanation?

    (i'm using code::blocks with mingw if that matters)

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Do a ss.clear() to clear the error state of the stringstream before using str().
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    28
    thank you!
    that was it. everything is working now. i didn't expect any error state in such a simple case.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 08-19-2012, 06:15 AM
  2. Odd Behavior for scanf("%c", &var)
    By Irno in forum C Programming
    Replies: 4
    Last Post: 04-09-2010, 02:45 PM
  3. "itoa"-"_itoa" , "inp"-"_inp", Why some functions have "
    By L.O.K. in forum Windows Programming
    Replies: 5
    Last Post: 12-08-2002, 08:25 AM
  4. "CWnd"-"HWnd","CBitmap"-"HBitmap"...., What is mean by "
    By L.O.K. in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 07:59 AM