Okay this is similar to my last question but what I ended up doing was way too complex for something as simple as this. I simply need to get a single character or number (I will know which of these I am receiving) from the console after I press space, instead of pressing enter. I'm sure there must be a way to have the terminal read input after a space instead of a '\n'. I need to read inputs from the console in which the succeeding data types will vary depending on what the first input is, and I think reading the entire line, parsing it into strings, then parsing some of those into ints is a bit unnecessary.
So Is this actually not possible in C++ or have I just not found it yet?
EDIT:
For anyone who has had this problem I'm posting my solution, because I feel like an idiot now.
#include <iostream>
using namespace std;
int main() {
int command = 0, x = 0, y = 0, z = 0;
char c;
do {
cin >> command;
switch(command) {
case 1:
cin >> c >> x;
cout << c << " " << x << endl;
break;
case 2:
cin >> x >> y >> z;
cout << x << " " << y << " " << z << endl;
break;
}
} while (command); //Exits when command = 0;
return 0;
}
The following cin's inside the switch statement will read from the same buffer as the first cin, so there is no need to read what the command is beforehand anyway. As you can see this works fine for开发者_JAVA百科 different types and amounts of inputs after the first cin, so there's no need to use any other solution.
Just posting this for anyone else who may have the same problem, and not a great understanding of the way cin works.
Just issue multiple calls to getchar()
(or getch()
) in a loop and check the input every iteration.
Something like this (untested but should work):
int loop = 1
int spacehit = 0
char last_c = 0;
while(loop)
{
char c = getchar();
switch(c)
{
case ' ':
spacehit = 1;
printf("hit '%c' before 'space'!\n", last_c);
break;
case 'x':
printf("hit 'x' after 'space'!\n");
spacehit = 0;
break;
case 27: // escape
loop = 0;
break;
default:
// do something, e.g. append the key in c to a string
break;
}
last_c = c;
}
Edit: Added some code to print the char before hitting space in case that's what you were looking for.
精彩评论