如何通过Enter(C ++)中断循环? [英] How to break loop by Enter (c++)?

查看:79
本文介绍了如何通过Enter(C ++)中断循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户不想再添加时,我想打破循环:

I wanted to break the loop when the user doesn't want to add anymore:

#include<iostream>

using namespace std;

int main() {
    int i = 0, a = 0, h = 0;
    cout << "Enter numbers to be added:\n ";
    for(i=0; ??; i++) {
        cout << "\n" << h << " + ";
        cin >> a;
        h = h+a;
    }
    return 0;
}

推荐答案

使用std :: getline读取输入行,并在该行为空时退出循环.

Use std::getline to read an input line and exit the loop when the line is empty.

#include<iostream>
#include <sstream>

int main() {
    int a = 0, h = 0;
    std::cout << "Enter numbers to be added:\n ";
    std::string line;

    std::cout << "\n" << h << " + ";
    while (std::getline(std::cin, line) && // input is good
           line.length() > 0) // line not empty
    {
        std::stringstream linestr(line);
        while (linestr >> a)// recommend better checking here. Look up std::strtol
        {
            h = h+a;
            std::cout << "\n" << h << " + ";
        }
    }
    return 0;
}

并输出:

Enter numbers to be added:

0 + 1 2 3 4 5 6 7 8 9 

1 + 
3 + 
6 + 
10 + 
15 + 
21 + 
28 + 
36 + 
45 + 

请注意,这允许每行多个条目,并且看起来很丑陋,因此OP可能更感兴趣:

Note that this allows multiple entries per line and looks pretty ugly, so OP is probably more interested in:

#include<iostream>

int main() {
    long a = 0, h = 0;
    std::cout << "Enter numbers to be added:\n ";
    std::string line;

    std::cout << "\n" << h << " + ";

    while (std::getline(std::cin, line) && // input is good
           line.length() > 0) // line not empty
    {
        char * endp; // will be updated with the character in line that wasn't a digit
        a = std::strtol(line.c_str(), &endp, 10);
        if (*endp == '\0') // if last character inspected was the end of the string
                           // warning: Does not catch ridiculously large numbers
        {
            h = h+a;
        }
        else
        {
            std::cout << "Very funny, wise guy. Try again." << std::endl;
        }
        std::cout << "\n" << h << " + ";
    }
    return 0;
}

输出

Enter numbers to be added:

0 + 1

1 + 1 2 3 4
Very funny, wise guy. Try again.

1 + 2

3 + 44444

44447 + jsdf;jasdklfjasdklf
Very funny, wise guy. Try again.

44447 + 9999999999999999999999

-2147439202 + 

这篇关于如何通过Enter(C ++)中断循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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