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

标签 c scanf

如果我为任何 char scanf 打开输入类似“asdasd asd asdas sad”的句子,它将跳过其他 scanfs。

例如,如果我键入 obligation scanf this sentence 它将为 obligation scanf 编写 this and next scanf 将被跳过,但会自动be field with 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 时停止扫描(空格,换行符等)。请改用 %[ 格式说明符:

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

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

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

在这种情况下,它将扫描最多 1499 个字符(最后的 NUL 终止符 +1)。这可以防止 buffer overruns .您还可以检查 scanf 的返回值为 @EdHeal suggests in a comment检查是否成功。

关于c - 为什么如果我输入句子其他 scanf 被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099508/

相关文章:

C:提示输入一行并检查

c - 从文件中读取未知数量的整数

c - 在 C 中使用 fscanf 读取另一行

c++ - getchar_unlocked() VS scanf() VS cin

数组可以称为 const 指针吗?

c - 函数内部变量的变量类型

c - gcc 无法获取在包含目录参数中传递的文件

c - 相同的代码在 main 中有效,但在从 C 中的函数调用时无效

c - Scanf 在仅加载数字的程序中不会注意到 '\n' 字符

c - 如何在 Windows 上绘制突出显示/选定的位图?