Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

%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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...