Sumod
Sumod

Reputation: 3846

Reading multiple values in C using scanf

There is another thread explaining the way to get multiple values using scanf(). I tried that, however, I got correct value for the first variable and junk values for the remaining two variables. When I used separate scanf statements, it worked fine. I am using RH Linux 5. Kernel version - 2.6.18-238. 4.1.2

e.g. if I do scanf("%d %d %d",&n,&p1,&p2), then n is read fine. But p1 is assigned 32767 and p2 is assigned another number even after I read the values. But according to the thread on SO, it should work. So what am I doing wrong?

Upvotes: 1

Views: 8157

Answers (1)

NPE
NPE

Reputation: 500167

You don't say what types the three variables are. They have to be int.

The following code works as expected on my computer:

#include <stdio.h>

int main()
{
  int n, p1, p2;
  scanf("%d %d %d", &n, &p1, &p2);
  printf("%d %d %d\n", n, p1, p2);
  return 0;
}

Here is the output:

$ gcc x.c
$ ./a.out 
10 3 5
10 3 5

Upvotes: 2

Related Questions