Cin>>and types

Oct 30, 2010 at 7:23pm
Hello.

i wanted to learn how C++ takes in input, i understand, initial white spaces are skipped, and after it starts to read it will stop reading on the encounter of a white space, and the data is kept in the stream to be accessed by the next reader.

now i wrote a program to test the functionality of char,int,float,double,bool,and string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;



int main()
{
    char a;
    int b,o;
    float c;
    double d;
    bool e;
    string f;

    cin >>a>>b>>c>>d;
    cin >>e;
    cin >>f>>o;

    cout <<"the char: "<<a<<endl<<"the int: "<<b<<endl<<"float: "<<c<<endl<<"double: "<<d<<endl<<"bool: "<<e<<endl<<"string: "<<f<<endl<<"last int:"<<o<<endl;

    return 0;

}


now the problem with this one is this:

i am inputting::
1
2
3
4
5

now since char can read a single character or an integer, 1 is stored into char.
then 2 is read in by the int b and stored,
now the float reads in the 3 and stores it,
and the double reads in the 4.
bool can not read anything else than 0 or 1, thus bool reading fail and the data is given to the next one, thus String,
String can not read a numerical data, thus it fails and data is passed to the next reader.

now the last one is the int o, this should read in the value 5 and store it buts its not happening.


1
2
3
4
5
the char: 1
the int: 2
float: 3
double: 4
bool: 246
String:
last int:4248112



Also i though String can not read numerical values but it can example::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;



int main()
{
    char a;
    int b,o;
    float c;
    double d;
    bool e;
    string f;

    //cin >>a>>b>>c>>d;
    //cin >>e;
    cin >>f>>o;

    cout /*<<"the char: "<<a<<endl<<"the int: "<<b<<endl<<"float: "<<c<<endl<<"double: "<<d<<endl<<"bool: "<<e<<endl*/<<"string: "<<f<<endl<<"last int:"<<o<<endl;

    return 0;
}



12
23
String: 12
last int:23



i am really confused, can you point me in the correct direction. thank you very much in advance.
Oct 30, 2010 at 8:55pm
Once an input operation fails, the stream state changes from good to one of eof, fail, bad or a combination of them ( depending on the reason of the failure )
If a stream is not good all other operations will fail. You need to set its state back to good using clear():
http://www.cplusplus.com/reference/iostream/ios/clear/
Topic archived. No new replies allowed.