istringstream evaluating to boolean ?

This is a discussion on istringstream evaluating to boolean ? within the C++ Programming forums, part of the General Programming Boards category; My common convention when I want to take a string and tokenize it is as follows Code: string str = ...

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    266

    istringstream evaluating to boolean ?

    My common convention when I want to take a string and tokenize it is as follows

    Code:
    string str = "hello world";
    vector<string> vs;
    istringstream iss(str);
    while(iss)
    {
      string t;
      iss >> t;
      vs.push_back(t);
    }
    cout << vs.size();
    the vectors size is 3 in this case because the last string pushed into the vector is empty..

    what does iss evaluate to when its 'empty' that causes this last iteration of an empty string being pushed?

    thanks

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    iss does not enter a bad state (which is what your conversion to bool is checking) until a read has failed. This is the same sort of thing as the FAQ about "why shouldn't I use feof to run a while loop". You should have
    Code:
    while (iss >> t)
    because you don't care about the state of iss (necessarily) -- you care whether the reading into t was successful.

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    266
    thank tapstop for once again solving my problems!


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Novice needs help
    By ghaasemi in forum C++ Programming
    Replies: 9
    Last Post: 05-30-2009, 09:20 AM
  2. boolean evaluating objects
    By cyberfish in forum C++ Programming
    Replies: 7
    Last Post: 11-04-2007, 09:44 PM
  3. istringstream problem in switch block?
    By wolfindark in forum C++ Programming
    Replies: 4
    Last Post: 06-25-2007, 12:56 AM
  4. Replies: 1
    Last Post: 10-27-2006, 02:21 PM
  5. Use struct to create a boolean type
    By skyglin in forum C Programming
    Replies: 6
    Last Post: 06-18-2003, 09:21 PM

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