I'm not entirely sure how to phrase this, mostly because I don't understand what's happening.
However, I'm trying to write a simple program to run a number trick. In order to pace the program well, I have inserted "cin.get()" function calls after a number of the outputs. This is working well for a large portion of the program, but the first "cin.get" call I make is being ignored every time I run the compiled program.
#include <iostream>
#include <string.h>
usingnamespace std;
int mult (int x); //user-entered integer for number trick
int main()
{
int x; // declaring user-entered variable
char answer[1]; // declaring character variable
cout<<"Want to try a number trick? y/n \n";
cin>> answer;
if (stricmp ("y", answer) == 0 ) //if statement comparing character strings
{
cout<<"Ok! Please enter an integer.\n";
cin>> x;
cout<<"Great," << x <<" is a great number. This trick will turn " << x << " into 7.\n";
sleep(2); //Wait so user can read
cout<<"First, I'm going to add 9.\n = " << x + 9 <<" (enter to continue)\n";
cin.get(); //Wait until user hits enter
cout<<"Great, now I'm going to multiply by 2.\n = " << (x + 9) * 2 <<" (enter to continue)\n";
cin.get();
cout<<"Now, I'm going to subtract 4.\n = " << ((x + 9) * 2) - 4 <<" (enter to continue)\n";
cin.get();
cout<<"Next I'll divide by 2.\n = " << (((x + 9) * 2) - 4) / 2 <<" (enter to continue)\n";
cin.get();
cout<<"And now the last step, I will subtract " << x <<"\n = "<< (((((x + 9) * 2) - 4) / 2) - x) <<" (enter to continue)\n";
cin.get();
cout<<"TA-DA! Be amazed!\n";
}
else //other side of if statement
cout<<"Well forget you, then.";
}
I'm sure it's rather clumsy, and the solution is probably pretty obvious. However, I'm very new to coding, and I haven't had any luck on the forums, so any and all help is greatly appreciated. Thank you!
It doesn't work because the cin>>x; leaves the newline the buffer. The first cin.get() reads that as the user having pressed enter. You can use cin.ignore() to throw away input before you wait for an enter.