Is there a command to invoke the press of an enter key? What is it.
Or do I insert a macro in my code to do that (too bad I can't figure out how to insert a macro to do that)
Printable View
Is there a command to invoke the press of an enter key? What is it.
Or do I insert a macro in my code to do that (too bad I can't figure out how to insert a macro to do that)
What do you want to do? Make other apps think enter was pressed? Write a newline to a console? Make your own app think enter was pressed?
Originally I wanted to get numeric only input from a keyboard and display an error message if the input contained any characters other than 0 to 9.
A member of this forum PARKSIE gave me the code below. The code below requires the user press the enter key twice after entering the number, or the incorrect combination of numbers & letters. Therefore, I wanted to insert a line of code that will produce the second press of the enter key after the first press of enter.....
I do not want the user needing to press enter twice.
I eventually ended up using different code which can be seen after the code given to me by PARKSIE.
Being an absolute begginer, any comments you may have on the code I am using (second listing) would be appreciated...
//Code from Parsie below
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
cout << "Please enter an integer: " << flush;
int num;
cin >> num;
//cout<< enter;
cout << endl;
// get the rest of the stream
string s;
getline(cin, s);
if(!s.empty() || cin.fail())
{
cout << "You didn't enter a number!" << endl;
return -1;
}
cout << "Final number: " << num << endl;
return 0;
}
//***********************
// My code minus the #include directives
char digit_string[50]; //overkill size of array
int index = 0;
while (next != '\n')
{
if ( (!isdigit(next)) && (index < 49) )
cout << "Input Error" ;
digit_string[index] = next;
index++;
cin.get(next);
}
digit_string[index] = '\0';
return;
// end of snippet
I is a known problem of getline that it has a problem concerning input buffering. Try this code, it won't work if the input contains spaces though:
You don't need the <sstream> include here (you didn't need in parksie's code either, it's just that he loves this file :D).Code:int main() {
cout << "Please enter an integer: " << flush;
int num;
cin >> num;
cout << endl;
// get the rest of the stream
string s;
cin >> s;
if(!s.empty() || cin.fail())
{
cout << "You didn't enter a number!" << endl;
return -1;
}
cout << "Final number: " << num << endl;
return 0;
}
As I said, this code may have problems with whitespaces: it will say that it isn't a number even though it is (but that may be what you want anyway, right?)
Actually, the getline version parksie uses probably doesn't have this problem, he uses a better standard library than the one shipped with VC++ (but it isn't free).