Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

c - Why if I enter sentence other scanf is skipped

If I open enter sentence something like this "asdasd asd asdas sad" for any char scanf it will skip other scanfs.

for exapmle if I type for obligation scanf this sentence it will write for obligation scanf this and next scanf will be skipped but automaticly will be field with sentence word...

Here is the code:

while(cont == 1){
    struct timeval tv;
    char str[12];
    struct tm *tm;

    int days = 1;
    char obligation[1500];
    char dodatno[1500];

    printf("Enter number of days till obligation: ");
    scanf(" %d", &days);
    printf("Enter obligation: ");
    scanf(" %s", obligation);
    printf("Sati: ");
    scanf(" %s", dodatno);

    if (gettimeofday(&tv, NULL) == -1)
        return -1; /* error occurred */
    tv.tv_sec += days * 24 * 3600; /* add 6 days converted to seconds */
    tm = localtime(&tv.tv_sec);
    /* Format as you want */

    strftime(str, sizeof(str), "%d-%b-%Y", tm);

    FILE * database;
    database = fopen("database", "a+");
    fprintf(database, "%s|%s|%s 
",str,obligation,dodatno);
    fclose(database);

    puts("To finish with adding enter 0 to continue press 1 
");
    scanf(" %d", &cont);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

%s stops scanning when it encounters a whitespace character (space, newline etc). Use the %[ format specifier instead :

scanf(" %[^
]", obligation);
scanf(" %[^
]", dodatno);

%[^ ] tells scanf to scan everything until a newline character. It is better to use the length modifier which limits the number of characters to read:

scanf(" %1499[^
]", obligation);
scanf(" %1499[^
]", dodatno);

In this case, it will scan a maximum of 1499 characters (+1 for the NUL-terminator at the end). This prevents buffer overruns. You can also check the return value of scanf as @EdHeal suggests in a comment to check if it was successful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...