stringstream-conversion from char to int

Oct 6, 2015 at 8:08pm
I am trying to get an 'integer' input from user in a string by using getline() and then using stringstream() to extract integer from this string. The last part of the following link suggests this method as
"With this approach of getting entire lines and extracting their contents, we separate the process of getting user input from its interpretation as data, allowing the input process to be what the user expects, and at the same time gaining more control over the transformation of its content into useful data by the program."

 
http://www.cplusplus.com/doc/tutorial/basic_io/ 


Based on this input's value, i call a function sum.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  int Sum (int);

int main(int argc, char *argv[])
{
    int myInt;
    string myString;
    int result;

    cout<<"Enter the length of numbers to be added : "<<endl;
    getline(cin,myString);
    stringstream(myString) >> myInt;
    if(myInt > 0)
    {
        result = Sum (myInt);
        cout<<"The Result is : "<< result << endl;
    }
    else
    {
        cout<<" Input is 0 or less " << result << endl;
    }

    return result;
}


Now in the test case, if the user enters 'k', converting it into int the code above goes to the 'else' condition.i.e. it says that the value is not greater than '0'. This is fine for my code but when i try to cout this value, it gives me a very large value(garbage like). '1974616370' in this case. Can anyone explain what actually is happening in the background here??

i.e. what happens when a character is inserted into int variable like in this case and how to do exception handling, if any, for such situations?

Also should i not get a runtime error or something when a char is inserted into an int variable??
Oct 6, 2015 at 8:46pm
what happens when a character is inserted into int variable
If there were digits prior to that character in current read operation, then it is treated as number end, digits read so far goes into variable, encountered character remains in stream, everything is normal.
If there weren't any digits (first character encountered is non-digit) then stream is set to failed state, and variable either remains the same or set to 0 (depending on C++ standard version)

Also should i not get a runtime error or something when a char is inserted into an int variable??
You do. Stream state is set to failure. You can check it by either converting stream to bool or by callin .fail() member function.
Oct 9, 2015 at 12:47pm
Got it.Thanks a ton.
Topic archived. No new replies allowed.