使用Enter(返回键)C ++退出循环

时间:2015-07-17 15:38:39

标签: c++

首先感谢您的回答和帮助...... 现在我正在制作一个程序,让用户输入任意数字......然后使用该程序指出输入数字中的4个总数,我现在遇到了问题..

这是我在这里发表的第一篇文章,如果我犯了任何错误,请原谅我。

守则

int main()
{
    int T,i,j,l;
    char N,p[10];
    cin>>T;
    while(T--)   //The number of times a user can enter a new number
    {
        cout<<"\nEnter Numbers\n";
        l=0;i=0;
        do
        {
            N=getch();  //getch is used so that the enter key need not be pressed and the 
                        //number looks like a whole and also so the each number is 
                        //individually stored  
            p[i]=N;    //here the number entered is stored in p
            cout<<N;  //to display the number obviously
            l++;i++;
        }while(N!=' ');  //Now here between '' something has to be present so that the loop 
                         //terminates as soon as the enter key is pressed right now as soon 
                         //as the spacebar is hit the loop will terminate. 
        cout<<"\n";
        j=0;
        for(i=0;i<l;i++)  //using l so that the loop runs accordingly
        {
            if(p[i]=='4') 
            {
                j++;    //for couting the number of 4's
            }
            cout<<p[i]<<"\n";   //wont be needing in the final program but here cout is just
                               // to check the output
        }
        cout<<"\n THERE ARE "<<j<<" FOURS\n";
    }
}


请不要说我已经有了我的程序的解决方案所以请不要使用一些不同的逻辑提供不同的代码...我真的需要这个相同的程序才能工作。我知道这个程序可以是使用字符串长度工作但在这里我想要在按下回车键后终止循环。

2 个答案:

答案 0 :(得分:2)

如果您想在用户按Enter而不是空格时停止输入,则需要针对'\r''\n''\r\n'进行测试,具体取决于您使用的操作系统。如果你要使用C ++,那说你真的应该使用标准的C ++。您可以轻松地将代码设置为:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    int loops;
    std::cout << "How many numbers to check: ";
    std::cin >> loops;
    std::cin.get(); // eat newline
    for (int i = 0; i < loops; i++)
    {
        std::string numbers;
        std::cout << "Enter numbers and press enter: ";
        std::getline(std::cin, numbers);
        auto numberOf4s = std::count(numbers.begin(), numbers.end(), '4');
        std::cout << "Number of 4's entered: " << numberOf4s << std::endl;
    }
    return 0;
}

Live Example

答案 1 :(得分:0)

您可以查看N是否等于'\r'。所以你的while循环看起来像

    do
    {
        N=getch();  //getch is used so that the enter key need not be pressed and the 
                    //number looks like a whole and also so the each number is 
                    //individually stored  
        p[i]=N;    //here the number entered is stored in p
        cout<<N;  //to display the number obviously
        l++;i++;
    }while(N!='\r');