dimanche 22 décembre 2019

Is there some input condition for which `cin >> someStringValue` can evaulate to `false'?

In C++, standard input stream i.e. cin could evaluate to false (via. implicit boolean conversion) if it finds an input value that is not matching with type of variable where input is going to be stored.

For example,

#include <iostream>
using namespace std;

int main() {
    int x;

    while (cin >> x)
    {
        cout << "valid integer input\n";
    }

    cout << "invalid integer input !!\n";
    return 0;
}

Input/Output to above code,

Input,

12
13
15
ABC

Output,

valid integer input
valid integer input
valid integer input
invalid integer input !!

Here is my question,

As expected, If we give a non-numeric input in above scenario then cin evaluates to false and program ends there. But what if I use a string variable in-place of integer variable in above code then what could be possible input value which I can provide so that cin evaluates to false? Because when I try above piece of code with a string variable instead of int then while-loop never seems to end ...

Aucun commentaire:

Enregistrer un commentaire