按下Enter键后退出循环 [英] Exit out of a loop after hitting enter in c

查看:391
本文介绍了按下Enter键后退出循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何仅通过按Enter键退出循环: 我尝试了以下代码,但无法正常工作!

How should i exit out of a loop just by hitting the enter key: I tried the following code but it is not working!

  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;
    }

我必须按如下所示进行输入:

I have to take input as follows:

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

推荐答案

您最好的选择是使用fgets进行基于行的输入,并检测行中唯一的东西是换行符.

Your best bet is to use fgets for line based input and detect if the only thing in the line was the newline character.

如果没有,则可以sscanf输入行以获取整数,而不是直接scanf输入标准输入.

If not, you can then sscanf the line you've entered to get an integer, rather than directly scanfing standard input.

可以在

A robust line input function can be found in this answer, then you just need to modify your scanf to use sscanf.

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

If you don't want to use that full featured input function, you can use a simpler method such as:

#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;
}

这篇关于按下Enter键后退出循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆