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

This is a discussion on "std::stringstream" unexpected behavior (simple example) within the C++ Programming forums, part of the General Programming Boards category; hi Guys, i'm puzzled by the values i'm getting back from stringstream Code: #include <sstream> #include <iostream> int main(int argc, ...

  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
    21,749
    Do a ss.clear() to clear the error state of the stringstream before using str().
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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, 07: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, 06:59 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21