how to use scanf()?

G

Guest

I recently find that if I use scanf() in a for loop,the function
doesnot work as I
wish.
for example:
struct person{
int price;
long milk;
struct person *next;
};

struct person *head;
struct person *pre;
struct person *now;
struct person *come;


for(i=1;i<=M;i++){
come=new struct person;
scanf("%d %ld ",&come->price,&come->milk);
ey);
…………
}
In the first time I have to input four numbers ,but the scanf() only
read the first two,and in the sencond time I also input two number,but
the scanf() read the last two of the first time?
Why is it?
~~
sorry ,My English is poor.
 
K

Keith Thompson

ç—žå­ said:
I recently find that if I use scanf() in a for loop,the function
doesnot work as I
wish.
for example:
struct person{
int price;
long milk;
struct person *next;
};

struct person *head;
struct person *pre;
struct person *now;
struct person *come;


for(i=1;i<=M;i++){
come=new struct person;
scanf("%d %ld ",&come->price,&come->milk);
ey);
…………
}
In the first time I have to input four numbers ,but the scanf() only
read the first two,and in the sencond time I also input two number,but
the scanf() read the last two of the first time?
Why is it?

First, the expression "new struct person" is specific to C++; it's a
syntax error in C. For C, you want
come = malloc(sizeof *come);
and a "#include <stdlib.h>" at the top.

You entered 4 numbers. Your first scan() read the first two, and your
second scanf() read the next two. That's exactly what it's supposed
to do.

If you want line-orientd input, use fgets(), and then parse the input
line with sscanf().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top