C Language String and Integer Input Questions

Asked 2 years ago, Updated 2 years ago, 42 views

I just started studying C language at university It is a matter of defining a structure related to a book and writing a code that receives related information directly from a user.

typedef struct book{

char name[30];
char writer[30];
int length;

}Book;

int _tmain()

{

int i,j;    
Book books[30];
for(i=0;i<3;i++)
{
    fgets(books[i].name,30,stdin);
    fgets(books[i].writer,30,stdin);
    scanf("%d", &books[i].length);
}
for(i=0;i<3;i++)
{
    printf("%s", books[i].name);
    printf("%s", books[i].writer);
    printf("%d", books[i].length);
}
return 0;

}

Like this.

Yoon C programming 200 Hong C++ programming 250 James OS for programmer 300

I typed it like this...

Yoon C programming 200 Hong -85993...... 250 -85993......

This is how it works.I think there's something wrong with the fixed income power, but why is it like this?

string

2022-09-22 19:50

1 Answers

Because of the nature of the function scanf.

The scanf function uses a buffer, which is input only when there are no characters in that buffer.

That is, if you hit 100 yen while waiting for input due to scanf, 100 and the opening letter \n are also buffered.

Eventually, 100 will be stored in the length field within the structure, and the next book structure name field will have an unwanted form.

Now that we know the cause, let's think about a solution. Scanf said to stack keystrokes in the buffer, so you can get the length value and empty the keyboard buffer.

for(i=0;i<3;i++)
{
    fgets(books[i].name,30,stdin);
    fgets(books[i].writer,30,stdin);
    scanf("%d", &books[i].length);
    Getchar(); // intentionally empty one character from the buffer 
    fflush(stdin); // You can empty the buffer. 
}


2022-09-22 19:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.