【问题标题】:C: loop on scanfC:在scanf上循环
【发布时间】:2016-05-18 18:52:34
【问题描述】:
    char buf[1024] = {0};

    // send a message
    if(status == 0) {
        while(1) {
            printf("Enter message : ");
            scanf("%1023[^\n]", buf);
            fflush(stdin);
            if(strcmp(buf,"quit")==0)
                break;
            status = write(s, buf, strlen(buf));
            fflush(stdout);
            memset(buf,0,sizeof buf);
        }
    }

对于我的 scanf,我想使用空格。但是,如果我运行这部分代码,“输入消息:”将处于无限循环中。

如果我只将 scanf 更改为“%s”,那么它可以正常工作,但我无法接受中间有空格的输入。

任何人都可以帮助发现它是如何抛出无限循环或解决这个问题的任何想法吗?

【问题讨论】:

  • 不要使用fflush(stdin),这是未定义的行为
  • 你为什么使用writefwrite
  • 我猜换行符会留在缓冲区中,因此后续对scanf 的调用会读取零个字符。
  • @user3121023 完美解决方案是fgets()
  • fflush(stdin) 与某些平台/编译器一起使用以刷新stdin。然而,C 标准并没有具体说明,而是未定义的行为。它不是便携式的。

标签: c scanf


【解决方案1】:

scanf() 阅读一行 时出错的方法太多了。使用fgets()

char buf[1024] = {0};

// send a message
if(status == 0) {
    while(1) {
        printf("Enter message : ");
        if (fgets(buf, sizeof buf, stdin) == NULL) break;
        //scanf("%1023[^\n]", buf);
        //fflush(stdin);

        buf[strcspn(buf, "\n")] = '\0'; // lop off potential \n

        if(strcmp(buf,"quit")==0)
            break;


        status = write(s, buf, strlen(buf));
        // fflush(stdout);
        memset(buf,0,sizeof buf);
    }
}

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 2020-02-16
    相关资源
    最近更新 更多