So I am still learning about C++. I'm trying to substitute cin with getline. So instead of storing values using cin, I use getline. And it doesn't work, can you explain? This is my first post of question and I'm still new, this is my first account. Thank you.
#include <iostream>
#include <string>
#include<conio.h>
using namespace std;
int main()
{
string answer1, answer2, sum;
cout << "Enter first number: " << endl;
getline (cin,answer1);
cout << "Enter second number: " <<endl;
getline (cin, answer2);
sum=answer1+answer2;
cout << "The sum is: " << sum <<endl;
getch();
}
Output is:
Enter first number:
1
Enter second number:
2
The sum is: 12.
The sum is wrong, it didn't even use ADDITION.
But I understand that getline is awesome because when you store something, it includes the spaces unlike cin.
My observation is that: "Did it identify "answer1" and "answer 2" variables as a string BUT not as an integer?" If I used integer, I can't use the "getline" anymore. So... what should I do.
Because I think getline can do MORE, like for example both "string" and numeric values to perform arithmetic operations on them. Is there a way to identify them as numeric value without changing string into "integer" type?
For example:
cout << "Enter first number: " << endl;
getline (cin, answer1) <<<< in this part, how can you convert it to integer. THEN...
cout << "Enter second number: " << endl;
getline (cin, answer2) <<<<< in this part again, make it integer before performing it in arithmetic operation..
sum=answer1+answer2
cout << "The sum is: " << sum << endl << "." endl;
So in the end it will identify as integer and display the SUM.
The fundamental problem is the user. The user can and will write "fubar" even though your program clearly prompts to enter an unsigned int.
There are many ways to perform the conversion, but the real challenge is how you test for and handle the erroneous input. The atoi() does not indicate failure. The stoi() throws an exception. The operator>> formatted input sets the failbit of the stream.
Note that the getline() can fail too for other reasons.
Ok, phase 1 is done; you detect error in some way.
Then you have phase 2 to decide: what to do next?
Do you abort the program, or keep asking the same data again, until the user complies?
1. istreamobj >> answer
2. if error
clear istreamobj error flags
ignore current istreamobj content
repeat from 1