【问题标题】:problems with scanf and fgetsscanf 和 fgets 的问题
【发布时间】:2019-10-20 13:00:00
【问题描述】:

我周二有一个项目到期,除了这个小地方外,一切正常。

void main ()
{
    struct CHANNEL uChan;
    int flag = 0;

    //get name of channel
    printf("Enter the name of the channel: ");
    fgets(uChan.name, 15, stdin);

    //positive check loop from cylinderVolume.c
    do
    {
        flag = 1;
        printf("Please give roughness coefficient n, channel slope, width of channel and the maximum depth: ");
        scanf("%lf %lf %lf %lf ",&uChan.n, &uChan.slope, &uChan.width, &uChan.maxDepth);

        if(uChan.n <= 0.0 || uChan.slope <= 0.0 || uChan.width <= 0.0 || uChan.maxDepth <= 0.0)
          {
              printf("All values must be greater than zero.\n");
              flag = 1;
          }
        else
            flag = 0;
    } while(flag == 1);

    return;
}

(uCha​​n是一个结构体,它的所有成员都在这里定义) 当我运行它(使用我的其余代码)时,它将在 scanf 行中请求 5 个输入,无论我输入 fgets 什么,它都会输出'á'

【问题讨论】:

  • struct CHANNEL - 请显示结构。还有void main -> 应该是int main
  • 您的 scanf 行读取 4 个(不是 5 个)值。
  • 同时检查返回 vom scanf。这是有原因的
  • printf("Pl....之后你还需要一个fflush(stdout);
  • 总会输出'á'在哪里?程序只输出常量字符串。

标签: c scanf fgets


【解决方案1】:

scanf(和系列)格式字符串中的空白字符指示scanf 读取并忽略所有空白字符,直到出现非空白字符为止。

在你的情况下,

scanf("%lf %lf %lf %lf ",&uChan.n, &uChan.slope, &uChan.width, &uChan.maxDepth);
                  //  ^ this space is causing scanf to wait until a non whitespace character

要修复它,请删除空格

【讨论】:

  • 它确实解决了 some 问题,但不一定是 OP 询问的问题。
  • 很确定它修复了 OP 的“五”输入问题。关于fgets 问题,我无话可说,因为我看不到完整的代码。至于其他的问题,cmets 好像已经涵盖了。
猜你喜欢
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
相关资源
最近更新 更多