【问题标题】:Exit out of a loop after hitting enter in c在 c 中按 enter 后退出循环
【发布时间】:2013-05-18 05:27:26
【问题描述】:

我应该如何通过按回车键退出循环: 我尝试了以下代码,但它不起作用!

  int main()
    {
        int n,i,j,no,arr[10];
        char c;
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
           j=0;
           while(c!='\n')
           {
            scanf("%d",&arr[j]);
            c=getchar();
            j++;
           }
          scanf("%d",&no);
        }
        return 0;
    }

我必须接受如下输入:

3//No of inputs
3 4 5//input 1
6
4 3//input 2
5
8//input 3
9

【问题讨论】:

  • 第一件事:提供您对程序不满意的输入和输出。第二件事:在使用之前初始化 char c,因为它包含随机值。第三件事:我已经尝试过你的代码,它可以按照你的意愿工作。
  • 接下来:你用哪个操作系统来编程?

标签: c input


【解决方案1】:

最好的办法是使用fgets 进行基于行的输入,并检测行中是否只有换行符。

如果没有,那么您可以通过sscanf 在您输入的行中获取整数,而不是直接scanfing 标准输入。

在this answer中可以找到一个健壮的线路输入功能,然后你只需要修改你的scanf来使用sscanf。

如果您不想使用全功能输入功能,可以使用更简单的方法,例如:

#include <stdio.h>
#include <string.h>

int main(void) {
    char inputStr[1024];
    int intVal;

    // Loop forever.

    for (;;) {
        // Get a string from the user, break on error.

        printf ("Enter your string: ");
        if (fgets (inputStr, sizeof (inputStr), stdin) == NULL)
            break;

        // Break if nothing entered.

        if (strcmp (inputStr, "\n") == 0)
            break;

        // Get and print integer.

        if (sscanf (inputStr, "%d", &intVal) != 1)
            printf ("scanf failure\n");
        else
            printf ("You entered %d\n", intVal);
    }

    return 0;
}

【讨论】:

  • 但是我怎样才能接受上述表格中的输入!?
  • @user2227862,查看更新,它给出了如何进行行输入、空行检测和转换的代码。
【解决方案2】:

换行符(\n 或 10 位十进制 Ascii)和回车(\r 或 13 位十进制 Ascii)之间存在差异。 在您的代码中,您应该尝试:

    switch(c)
    {
      case 10:
        scanf("%d",&no);
        /*c=something if you need to enter the loop again after reading no*/
        break;
      case 13:
        scanf("%d",&no);
        /*c=something if you need to enter the loop again after reading no*/
        break;
      default:
        scanf("%d",&arr[j]);
        c=getchar();
        j++;
        break;
    }

您还应该注意,您的变量 c 在第一次测试中没有被初始化,如果您不期望任何以 '\n' 或 '\r' 开头的输入,最好在之前为其赋予一些值第一次测试。

【讨论】:

  • while 循环中的条件始终为 false,因为 c 不能同时为 10 和 13 或 '\n' 和 '\r'。
【解决方案3】:

改变

j=0;

到

j=0;c=' ';//initialize c, clear '\n'

【讨论】:

    【解决方案4】:

    当程序退出while循环时,c包含'\n',所以下次程序不能进入while循环。您应该为c 分配一些值,而不是'\n' 以及for 循环内的j=0。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2010-11-23
      相关资源
      最近更新 更多