So, I'm trying to make a program that can do simple division. The problem is that if the user wants to rerun the code (without launching it again), there is some unwanted text that appears after asking the user to input the first number again.
it shows this after a rerun: Enter first number: Please enter a number
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
double ask_for_number(string const &prompt)
{
double x;
string line;
while((cout << prompt << ": ") //inserts line 30 and 31
&& getline(cin, line) //reads whole line
&& !(istringstream{line} >> x)) //validate input
{
cout << "Please enter a number" << endl << endl;
}
return x; // repeats until all variables filled
}
int main()
{
bool calculate = true;
while (calculate)
{
double N1 = ask_for_number("Enter first number"); //
double N2 = ask_for_number("Enter second number");
double quotient = 0;
quotient = N1 / N2;
if (N2 == 0)
{
cout << "Quotient does not exist" << endl; // if divided by zero
}
else
{
cout << "Quotient is " << quotient << endl << endl; // if not divided by zero
}
bool loop = true; // user now decides if another calculation is needed
while ( loop )
{
char choice; // user variable
cout << "Enter 1 to continue" << endl; //options
cout << "Enter 2 to quit" << endl;
cout << "Your choice? "; cin >> choice; // user choice input
if (choice == '1')
loop = false; // condition to end program
elseif (choice == '2')
calculate = false, loop = false; // end both loops
else
cout << "\n Please pick either 1 or 2 to proceed" << endl << endl;
} // end of "while (loop)" in line 57
} // end of "while (running)" in line 24
return 0;
} // end of all
On line 51, cin >> choice will leave a newline in the buffer to be read in next time you ask for input. Check the second post here for the fix: http://www.cplusplus.com/forum/beginner/1988/
The idea is to ignore the rest of the line (not to keep the program open).