3
votes

I need to get two integers from the user separated by space. The problem is, that if they enter only one integer and press Enter I need to print out the message that they have to enter two values and ask them to do it again.

scanf("%d %d", &a,&b);

This is how I scan for the input. This code is inside a while loop, so basically I keep asking them for 2 valid numbers. It works perfectly, however if I type only 1 int and press Enter key nothing happens until I finally enter the second integer. Making two scanf() is not a good idea because I need values to be separated by a space. Is there any other way to break scanf() if the user presses Enter key? I need to use scanf() only.

3

3 Answers

1
votes

The solution is to not use scanf. Instead, use a more appropriate function such as fgets, which reads a single line of input terminated by Enter. After you get the line of input, you can then use sscanf to extract the integers (or any other method you like).

The scanf function is almost never the appropriate choice for interactive input.

1
votes

scanf("%d", &a); consumes leading whites-space when scanning for an int and lacks the ability to distinguish space from enter '\n'.

So scanf() for the leading characters first

for (;;) {
  char buf[2];
  if (scanf("%1[ ]", buf) == 1) Handle_leading_space();
  else if (scanf("%1[\n]", buf) == 1) Handle_leading_enter();
  else break;
}
// Now scan for an `int`
if (scanf("%d", &a) == 1) Handle_int(a).

The above does not handle tabs, carriage returns, and other white space.

Alternative, just look for every thing that is not numeric.

char buf[2];
while (scanf("%1[^-+0123456789]", buf) == 1) {
  Handle_non_numeric(buf);
}
// Now scan for an `int`
if (scanf("%d", &a) == 1) Handle_int(a).

IMO, best to read with fgets() and then parse. Not using fgets() might make for a code challenge, but is not a good restriction for real programs.

0
votes

scanf return value is an integer, you can check how many arguments were successfully scanned:

if (scanf("%d %d", &a,&b) != 2) {
   // error case
}

See http://www.cplusplus.com/reference/cstdio/scanf/ . Read the return value documentation