cmk
cmk

Reputation: 1

fgets() is coming earlier than it should

int main (void){
    
    Article article;
    char title[100], author[100], journal[100], newtitle[100];
    int year;
    
    fgets(title, 80, stdin);
    fgets(author, 80, stdin);
    fgets(journal, 80, stdin);
    scanf("%d\n", &year);
    
    article = create_article(title, author, journal, year);
    print_format_full(article);
    
    fgets(newtitle, 80, stdin);
    article = update_title(article, newtitle);
    
    print_format_simplified(article);
    // insert your code here
    
    return 0;

}

I wanted to use fgets() for the last string(new title) after performing the first print function (print_format_full(article);) , but if I run the program, the program is asking for 5 inputs right at the beginning of the program. Can anybody help me find where I got it wrong?

Upvotes: 0

Views: 36

Answers (1)

Madagascar
Madagascar

Reputation: 7345

scanf() reads exactly what you ask it to, it leaves a newline in the input buffer, which is automatically read by fgets.

To consume the newline, either change the sequence, use fgets before scanf, or use fgets to read the number and then Parse it with sscanf, strtol etc.

A while loop and getchar works too.

Upvotes: 1

Related Questions