Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C printf wont print before scaning next number

I got this piece of code

#include<stdio.h>
#include <stdlib.h>

int main()
{
  int i;
  int number, S;
  float MO;


  S = 0;

  for(i=0;i<10;i++)
  {
    printf("AAA %d\n", i );
    scanf("%d\n", &number);
    S = S + number;
  }

  MO = S/10;

  printf("%d , %f \n",S , MO );
  return 0;
}

when the execution starts, AAA 0 is printed.I then give my first number.After that, i am expecting to see AAA 1 , but this will be printed only after i give my second number. Checked this here

C/C++ printf() before scanf() issue

but seems i can get none of these solutions work for me

like image 663
user7375077 Avatar asked Dec 24 '22 21:12

user7375077


2 Answers

The answers claiming that this has something to do with flushing input or output are wrong. The problem has nothing to do with this. The appearance of the \n character at the end of the scanf() template string instructs scanf() to match and discard whitespace characters. It will do so until a non-whitespace character is encountered, or end-of-file is reached. The relevant part of the C11 Standard is §7.21.6.2 5:

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.

In OP's case, a second number must be placed in the input stream so that the first can be assigned. The second number then remains in the input stream until the next call to scanf(). In the case of the example given by Stephan Lechner, taking input from a file, there is a number in the input stream after each number to be assigned, until the last number (if there are exactly ten numbers), and then the EOF causes scanf() to return. Note that OP could also have signalled EOF from the keyboard after each input. Or, OP could enter all numbers on one line, with an extra number to signal end of input:

1 2 3 4 5 6 7 8 9 10 11

The solution is simply to remove the \n from the end of the scanf() template string. Whitespace characters at the end of such a template string are tricky, and almost never what is actually desired.

like image 66
ad absurdum Avatar answered Dec 28 '22 08:12

ad absurdum


Just remove the \n from the scanf format string:

scanf("%d", &number);
like image 39
Jabberwocky Avatar answered Dec 28 '22 08:12

Jabberwocky