-1

I'm trying to scan 4 numbers without pressing enter (I want it to end the scan when it sees there are 4 numbers). I'm using the method:

printf("Enter 4 Numbers(with space):\n");
scanf("%d %d %d %d" , &guess1 , &guess2 , &guess3 , &guess4);

but it requires spaces between the numbers and pressing enter at the end. So how do I make it to receive for example: 1234 (num1 = 1 , num2 = 2 and so on) and end the receiving without pressing enter.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    To start with, can the "numbers" be actual numbers, or just single digits? – Some programmer dude Jan 02 '16 at 20:55
  • 4
    Also, there's no standard function to read characters (translated into numbers or not) without pressing the enter key, you need to use platform-specific and probably non-portable functions for that. – Some programmer dude Jan 02 '16 at 21:04
  • 2
    Think about it: after you enter say `123` for the last input, how should the program know you don't intend to enter `1234` (even if you paused to sip coffee while contemplating the last digit)? – Weather Vane Jan 02 '16 at 21:06

3 Answers3

1

To enter in "1234" and scan as 4 digits use a "1"` to limit the text width of data input for each integer.

if (scanf("%1d%1d%1d%1d" , &guess1 , &guess2 , &guess3 , &guess4))!=4) Handle_Input_Error();
else Success();

stdin is usualy line buffered. So to read data without waiting for the Enter, the solution is platform specific.

See How can I prevent scanf() to wait forever for an input character?

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

You cannot do this the way you imagined, because your process is not getting anything before you press enter. This is how buffering works. If you really want to do this (and you haven't given a reason), you may consider an OS-specific console UI library like ncurses for Linux, or an equivalent for DOS, which will allow you to capture each keypress. Then you would have to assemble numbers by collecting individual digits into it. It is not easy though and would transform your entire program into something you might not want. Give us a reason why you want to make this the way you described?

Darko Maksimovic
  • 1,155
  • 12
  • 14
0

Its simple just remove the spaces between %d in scanf() and u can enter numbers like 1 2 3 4 and then press enter, numbers will be stored in guess1, guess2, guess3 and guess4 respectively. printf("Enter 4 Numbers(with space):\n");

scanf("%d%d%d%d" , &guess1 , &guess2 , &guess3 , &guess4); 

so u have to just learn Technic to read numbers separated with spaces.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Mike
  • 169
  • 10