-2

これが作業コードです

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct birthdate{
        int day;
        int month;
        int year;
        }birthdate_t;

typedef struct contacto {
        char name[30];
        long telephone;
        birthdate_t bd;  // es decir, bd es de tipo struct
        } contacto_t;

/* create the prototypes. Otherwise it does not work! */
contacto_t create_contact(void);
birthdate_t create_birthdate(void);

        contacto_t create_contact(){ // it returns a structure type
        contacto_t c1; // creates actually a blank structure y aquí abajo le meto datos

        printf("Enter name: ");
        fgets(c1.name, sizeof(c1.name), stdin);

        char line[256];
        printf("Enter telephone: ");
        fgets(line, sizeof line, stdin);
        if (sscanf(line, "%ld", &c1.telephone) != 1)
        {
            /* error in input */
        }

        printf("Enter birthdate");
        c1.bd = create_birthdate();
    }


        birthdate_t create_birthdate(){

            birthdate_t bd1;
            char dia[4];
            printf("Enter day: ");
            fgets(dia, sizeof(dia), stdin);
            sscanf(dia, "%d\n", &bd1.day);

            char mes[4];
            printf("Enter month: ");
            fgets(mes, sizeof(mes), stdin);
            sscanf(mes, "%d\n", &bd1.month);

            char anyo[6];
            printf("Enter year: ");
            fgets(anyo, sizeof(anyo), stdin);
            sscanf(anyo, "%d\n", &bd1.year);
            return bd1;
    } // end of birthdate function

main (void)
{
    create_contact();

}
4

1 に答える 1

0

常に fgets で読み取りますが、文字列、整数、または long を読み取る場合は、処理方法が異なります。

文字列を読み取る場合、一度 fgets を使用すると、sscanf を使用する必要はありません。

整数を読み取る場合は、sscanf を使用して整数に変換します。

また、シュワルツが話していたことについて: fgets の後に読み取るときの sscanf の構文。これには 3 つのパラメーターがあり、標準入力から読み込むパラメーターには、それを格納する変数とは異なる変数が必要です。

しかし、これが非常に混乱した理由は、fgets を使用して文字列を読み取った後も sscanf を使用していたことと、文字列が fgets によって読み取られるとコンパイラがそれを無視するため、問題を引き起こさなかった間違った構文を使用していたためです。 、ただし、問題を引き起こさなかった文字列に使用したのと同じ構文を使用しているにもかかわらず、sscanfは整数を読み取るときに問題を引き起こします。

彼の正しい説明をコピーして貼り付けると、次のようになります。

fgets は、指定されたストリーム (stdin など) から入力行を読み取り、それを指定された文字列変数 (文字の配列) に入れます。

したがって、1 行から文字列を読み取るだけの場合は、fgets の後に何もする必要はありません。以前の投稿の fgets は、読み取った行 (改行文字を含む) を指定された文字列変数に入れます。

ただし、(値の表示バージョンを構成する文字を保持する文字列とは対照的に) 真の数値が必要な場合は、最初に文字列として読み取り、次に文字列を「スキャン」して文字を真の数値に変換します。

また、sscanf の最初と最後の位置に同じ変数名を入れても意味がありません。

于 2013-09-02T23:29:37.463 に答える