• 0

[C++] input question


Question

Heyz.. Im lookin for a way to read an input number from the keyboard, but without displaying it, and without the need of pressing enter.

Something like choosing one of 4 numbers, and then do the respective operation (+ for 1, - for 2, * for 3 and / for 4), but i wanted it to do it as soon as i press the number, not displaying.. i hope i was clear :wacko: , thanks for any replies..

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Hey man, I hope this code I've written will help you with your question! :laugh: I've learned to track keyboard input two ways, one is using the windows.h header and the other is the conio.h header; conio is the easiest to implement. Below is an implementation of the conio.h library.

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
char trackedKey = ' ';
int num1, num2;

cout << "First number: ";
cin >> num1;
cout << endl;

cout << "Second number: ";
cin >> num2;
cout << endl;

cout << "Press \"1\" to add the two numbers" << endl;
cout << "Press \"2\" to subtract the two numbers" << endl;
cout << "Press \"3\" to multiply the two numbers" << endl;
cout << "Press \"4\" to divide the two numbers" << endl;
cout << "Press \"Q\" to quit out of the program" << endl << endl;

while(trackedKey != 'q')
{
	if(kbhit())
	{
  trackedKey = getch();

  switch(trackedKey)
  {
 	 case '1':
    cout << num1 + num2 << endl;
 	 break;

 	 case '2':
    cout << num1 - num2 << endl;
 	 break;

 	 case '3':
    cout << num1 * num2 << endl;
 	 break;

 	 case '4':
    cout << num1 / num2 << endl;
 	 break;
  }
	}
}

cout << "You pressed the Q key to quit out." << endl;

return 0;
}

kbhit() and getch() are both part of conio.h. The program will continue to run until you press the Q key to quit out; if you press any key the program will enter the if statement in the while() loop and perform the operation on whichever key you pressed! Both functions should be pretty self-explanatory.

Edited by Vector9
Link to comment
Share on other sites

  • 0

i had tried that getch() thing, but that didnt (and still doesnt) work, which is odd, because your code works, and the only difference seems to be the if(kbhit()) part.. i dont know what's that, but ill try and look into it..

anyways, thanks a lot!

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.