2

Here is an overloaded >>operator function:

std::istream& operator>>(std::istream& is, std::vector<int>& v){
  string s;
  if (! (is >> s) )
    return is;
   ...
  return is;
}

To my understanding, if(! (is >> s)) make no sense because the terminal or console will wait until the input from keyboards or other sources enter s. So value of condition in if() will ultimately be false. Who can help?

Finley
  • 795
  • 1
  • 8
  • 26

4 Answers4

3

The is >> s attempts to read the string s from stream is.

istreams operator>>() returns a reference to is.

istreams operator!() tests if the stream is in an invalid state. Specifically, it returns true if the stream's badbit or failbit has been set.

So,

 if (! (is >> s) )
     return is;

is functionally equivalent to

 is >> s;
 if (is.fail()) return is;    // is.fail() returns true if failbit or badbit are set

which means that the function immediately returns if reading a string from the stream fails. Note that this is distinct from reaching the end of the stream.

Peter
  • 35,646
  • 4
  • 32
  • 74
2

istream does not have to be a console. It can be a stringstream. And besides, the 'waiting for user input' is not seen by the application code. It is asleep while the input stream is being filled (by the operating system, underlying library, ...)

Anyhow: in case the input stream contains no data at all, this condition will be true.

std::string s; // empty!
std::stringstream ss(s);

std::vector<std::string> strings;
ss >> strings; // should be empty!
xtofl
  • 40,723
  • 12
  • 105
  • 192
1

To understand what if (!(is >> s)) means you need to understand what if (is >> s) means.

Since is is an std::istream, operator >> returns an std::istream. Hence, is >> s is an std::istream, which inside an if must produce a logical value true or false. This Q&A explains how it is done in different versions of C++. Essentially, std::istream evaluates to a true condition when the operation is successful.

Now that you know the meaning of is >> s, you can figure out that adding a negation flips that meaning: !(is >> s) would be true only when reading an s from is is unsuccessful. For strings an unsuccessful read means that the stream is in an invalid state, for example, because the end of stream has been reached.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-1

you are doing many things in one line

! (is >> s)

you take the inputstream and use it to assign the object s, the evaluate teh result of s in the if condition

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97