0

I just started learning c. I have a code here for taking input from users and printing it.

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

int main()
{
    int a[5];
    int i ;

    for(i=0;i<5;i++)
    {
         printf("enter the %d position no: ",i+1);
         scanf("%d \n",&a[i]);
    }

    for(i = 0;i<5;i++)
        printf("position %d : %d \n",i+1,a[i]);

}

Here is my output console.

enter image description here

But the output is giving misleading result. at line 2 when scanf is reding it is not showing the string "enter the %d position" it is directly asking for value.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
sikka karma
  • 115
  • 1
  • 12
  • 1
    lose the \n in your scanf. Read about the [effects of trailing white space in scanf](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) –  Jul 11 '18 at 04:34
  • 1
    use cout and cin it should work – seccpur Jul 11 '18 at 04:39

3 Answers3

2

Your scanf doesn't need the space and the newline character, just "%d".

for(i=0; i<5; i++)
{
     printf("enter the %d position no: ",i+1);
     scanf("%d",&a[i]);
}
Miket25
  • 1,895
  • 3
  • 15
  • 29
2

Quick fix to your problem: scanf("%d \n",&a[i]) -> scanf("%d",&a[i])

Also, remember to always check scanf for errors. It can be done like this:

if(scanf("%d", &a[i]) < 0) {
    // Print error message and/or exit or whatever you want to do
} else {
    // Do something else
}

In the long run:

Take some time studying input methods in C. They are a bit tricky and there are millions of pitfalls. In short, scanf is a good choice provided that the input is in the exact format that you expect. This makes it a bad choice for user input, because users are quite unpredictable.

Here is a link worth reading:

http://www.giannistsakiris.com/2008/02/07/scanf-and-why-you-should-avoid-using-it/

klutt
  • 30,332
  • 17
  • 55
  • 95
0

you can use like below:

for(i=0;i<5;i++)
{
   printf("enter the %d position on : ",i+1);
   scanf("%d",&a[i]);
   printf("\n");
}
Ankita Mehta
  • 442
  • 3
  • 16