The program works as it should whenever you enter an Int, but for the case you enter an invalid datatype I want it to ask for input again.
The scanf() function takes input from the standard input (keyboard) and store the value in a variable. The function waits for the user input until the user press the enter key. Entered value is being stored in a buffer. When enter key is being pressed, scanf() function starts to read.
You may've used the scanf inside a while loop or for loop or do while loop or if else statement or switch case statement or in a remote user defined function that doesn't satisfy the condition to enter into it. In that case that block will be skipped and scanf will not work.
You can wait for input in C++ by calling the cin::get() function, which extracts a single character or optionally multiple characters from the input stream. Basically, ::get() function blocks the program execution until the user provides input and specifically n character to indicate the end of the input.
Several ways to do so, here are some possible one-line approaches:
Use getch()
(need #include <conio.h>
).
Use getchar()
(expected for Enter, need #include <iostream>
).
Use cin.get()
(expected for Enter, need #include <iostream>
).
Use system("pause")
(need #include <iostream>
, Windows only).
PS: This method will also print Press any key to continue . . .
on the screen. (seems perfect choice for you :))
Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.
a do while loop would be a nice way to wait for the user input. Like this:
int main()
{
do
{
cout << '\n' << "Press a key to continue...";
} while (cin.get() != '\n');
return 0;
}
You can also use the function system('PAUSE')
but I think this is a bit slower and platform dependent
There is no "standard" library function to do this. The standard (perhaps surprisingly) does not actually recognise the concept of a "keyboard", albeit it does have a standard for "console input".
There are various ways to achieve it on different operating systems (see herohuyongtao's solution) but it is not portable across all platforms that support keyboard input.
Remember that C++ (and C) are devised to be languages that can run on embedded systems that do not have keyboards. (Having said that, an embedded system might not have various other devices that the standard library supports).
This matter has been debated for a long time.
You can try
#include <iostream>
#include <conio.h>
int main() {
//some codes
getch();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With