Why if I enter sentence other scanf is skipped

2019-09-11 06:07发布

问题:

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 \n",str,obligation,dodatno);
    fclose(database);

    puts("To finish with adding enter 0 to continue press 1 \n");
    scanf(" %d", &cont);
    }

回答1:

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

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

%[^\n] 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[^\n]", obligation);
scanf(" %1499[^\n]", 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.



回答2:

I recommend reading character by character. you can use the following function e.g.

//reads user input to an array
void readString(char *array, char * prompt, int size) {
    printf("%s", prompt);
    char c; int count=0;
    while ( getchar() != '\n' );
    while ((c = getchar()) != '\n') {
        array[count] = c; count++;
        if (size < count){ break; } //lets u reserve the last index for '\0'
    }
}
//in your main you can simply call this as 
readString(obligation, "Enter obligation", 1500);


回答3:

Each successive call to scanf() can have a leading space in the format string.

When the format string contains a space, any 'white space' in the input, where that space is in the input, will be consumed.

This includes tabs, spaces, newlines.



标签: c scanf