【问题标题】:How to use scanf() for 2 correct inputs in C [duplicate]如何在C中使用scanf()进行2个正确输入[重复]
【发布时间】:2018-10-29 08:52:05
【问题描述】:

我有一个程序,它采用 2 种不同格式的输入,第一个是三角形的 3 个(所以 6 个双数)点的坐标,第二个是三角形每一边的长度(所以 3 个双数) .

第一个格式如:{ [ 1.5; 2 ], [3;4.2], [ 0.5 ; 0.6 ] }

第二个可能是:{ 5, 4.7, 3.2 }

我如何识别输入了哪一个,而无需明确询问并且只执行一次 scanf? 谢谢!

【问题讨论】:

标签: c


【解决方案1】:

您可以使用fgetssscanf 来满足您的要求。

确保您使用sscanf 的格式说明符作为输入,即使缺少一个空格也会导致sscanf 中止扫描。

  char buf[100];
  double ptx1,pty1,ptx2,pty2,ptx3,pty3;
  double side1,side2,side3;

  fgets(buf,sizeof buf,stdin);

  int ret = sscanf(buf, " { [%lf; %lf ], [%lf;%lf], [ %lf ; %lf ] }", &ptx1,&pty1,&ptx2,&pty2,&ptx3,&pty3);

  if (ret < 6)
  {
      ret = sscanf(buf, " { %lf, %lf, %lf }", &side1,&side2,&side3);
      if (ret < 3) printf("wrong input\n");

      fgets(buf,sizeof buf,stdin);
      ret = sscanf(buf, " { [%lf; %lf ], [%lf;%lf], [ %lf ; %lf ] }", 
      &ptx1,&pty1,&ptx2,&pty2,&ptx3,&pty3);

      if (ret < 6) printf("wrong input\n");
  }
  else
  {
      fgets(buf,sizeof buf,stdin);
      ret = sscanf(buf, " { %lf, %lf, %lf }", &side1,&side2,&side3);
      if (ret < 3) printf("wrong input\n");
  }

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    相关资源
    最近更新 更多