Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf "extra input" required

Tags:

c

scanf

for some simple HW code I wrote I needed to get 7 arguments via the scanf function:

scanf("%d %d %d %d\n", &vodka, &country, &life, &glut);
scanf("%d\n", &ageof);
scanf("%d\n", &dprice);
scanf("%d\n", &mprice);

as you can see, I'm asking for 7 arguments in this order:

argument [space] argument [space] argument [space] argument (down line)

argument (down line)

argument (down line)

argument (down line)

BUT, when running the code, I'm suddenly required to input 8 of them, and I have no idea why....

any help anyone?

like image 285
Alon Leibovitsh Avatar asked Nov 24 '15 22:11

Alon Leibovitsh


1 Answers

As explained by @chqrlie and @Blue Moon a white space in the format, be it ' ', '\n', '\n' or any white-space does the same thing. It directs scanf() to consume white-space, such as '\n' from an Enter, until non-white-space is detected. That non-white-space character is then put back into stdin for the next input operation.

scanf("%d\n", ...) does not return until some non-white space is entered after the int. Hence the need for the 8th input. That 8th input is not consumed, but available for subsequent input.


The best way to read the 4 lines of input is to .... drum roll ... read 4 lines. Then process the inputs.

char buf[4][80];
for (int i=0; i<4; i++) {
  if (fgets(buf[i], sizeof buf[i], stdin) == NULL) return Fail;
}
if (sscanf(buf[0], "%d%d%d%d", &vodka, &country, &life, &glut) != 4) {
  return Fail;
}
if (sscanf(buf[1], "%d", &ageof) != 1) {
  return Fail;
}
if (sscanf(buf[2], "%d", &dprice) != 1) {
  return Fail;
}
if (sscanf(buf[3], "%d", &mprice) != 1) {
  return Fail;
}
// Use vodka, country, life, glut, ageof, dprice, mprice
return Success
like image 162
chux - Reinstate Monica Avatar answered Oct 08 '22 03:10

chux - Reinstate Monica