为什么如果我输入句子其他 scanf 被跳过

Why if I enter sentence other scanf is skipped

如果我打开 enter sentence something like this "asdasd asd asdas sad" for any char scanf 它将跳过其他 scanfs。

例如,如果我键入 obligation scanf this sentence,它将为 obligation scanf 写入,而下一个 scanf 将被跳过,但会自动成为带有 sentence word 的字段。 ..

代码如下:

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);
    }

%s 在遇到 whitespace character(space、换行符等)时停止扫描。请改用 %[ 格式说明符:

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

%[^\n] 告诉 scanf 扫描所有内容,直到换行符。最好使用长度修饰符来限制读取的字符数:

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

在这种情况下,它将扫描最多 1499 个字符(最后的 NUL 终止符 +1)。这会阻止 buffer overruns. You can also check the return value of scanf as @EdHeal 检查是否成功。

我建议逐字阅读。您可以使用以下功能,例如

//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 '[=10=]'
    }
}
//in your main you can simply call this as 
readString(obligation, "Enter obligation", 1500);

对 scanf() 的每次连续调用都可以在格式字符串中有前导 space。

当格式字符串包含 space 时,输入中的任何 'white space'(其中 space 在输入中)都将被消耗。

这包括制表符、spaces、换行符。