Home>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Book_data {
    char title [50];
    int price;
    struct Book_data * next;
} Book_data;
Book_data * allocNode (char * title, int price, Book_data * next) {
    Book_data * Node = (Book_data *) malloc (sizeof (Book_data));
    memcpy (Node->title, title, sizeof (Node->title));
    Node->price = price;
    Node->next = next;
    return Node;
}
int main () {
    Book_data * top = NULL;
    char title [50];
    int price;
    char c;
    while (1) {
        printf ("Book title price y/N:");
        if (scanf ("% s% d% c", title,&price,&c)! = 3)
            puts ("Erorr");
        top = allocNode (title, price, top);
        if (c =='N')
            break;
    }
    Book_data * node = top;
    for (;node;node = node->next) {
        printf ("% s", node->title);
        printf ("% d Yen \ n", node->price);
    }
    return 0;
}


Since I learned about scanf () in the previous question, I wrote a program using scanf and a list.
In the previous answerer
The return value of scanf is! = N (n = 1,2 ...) I wrote it because it was like this.
Please tell me the meaning of writing! = 3.

Also, please point out any problems with the source code.

c
  • Answer # 1

    Try entering non-numeric characters in the price, such as "Algorithm Book ¥ 980 y".
    What happens? It would be ridiculous.

    Therefore, you have to check whether the input was successful as follows.

          if (scanf ("% s% d% c", title,&price,&c)! = 3) {// Read failed?
                puts ("Erorr");
                scanf ("% * [^ \ n]");// Skip all invalid characters up to the line feed character
            }
            else // If the reading is successful
                top = allocNode (title, price, top);// Add to list


    Or

          if (scanf ("% s% d% c", title,&price,&c) == 3) // If the read is successful
                top = allocNode (title, price, top);// Add to list
            else {
                puts ("Erorr");
                int c;// Another way to skip all invalid characters up to the newline character
                while ((c = getchar ())! = EOF&&c! ='\ N');
            }

  • Answer # 2

    Please tell me the meaning of writing! = 3.

    scanf () returns the number of items read as the return value.
    In the case of "scanf ("% s% d% c ", title,&price,&c)", there are 3 input values, so if the return value is not 3, it is probably an error as reading failed.

    Reference: C language function dictionary

Trends