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??