让用户给出输入,直到他输入X [英] Make user give input until he enter X

查看:165
本文介绍了让用户给出输入,直到他输入X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个初学者在编程,刚刚开始我的课几天前..仍然学习的概念。所以.. uhm
我在c ++中编写一个代码,从用户的整数,直到他按x停止。然后程序将打印正数,负数和零数。
但我有一个小问题在这里...每当用户输入x,程序进入无限循环...
i尝试删除ZEROS部分,只是作为计数器阳性和负面,它工作良好。但我想计数零...

i'm a beginner in programming and just started my class a few days ago .. still learning the concept. so .. uhm i'm writing a code in c++ that takes integers from user until he press "x" to stop. and then the program will print the number of positives, negatives and zeros. but i've a little problem here ... whenever the user input "x" , the program goes into infinite loop ... i tried removing the "ZEROS" part and just made counters for positives and negatives and it worked good . but i want to count the zeros .....

所以我需要的简短。让用户给出包括0在内的数字,直到他给出字符X
这里是我的代码..我知道的东西不是那么容易..但我是一个新手:D

so what i need in brief. to let the user give numbers including 0 until he give in character X here is my code .. i know things ain't that easy .. but i'm a newbie :D

#include <iostream>

using namespace std;

int main() {
    int input, neg = 0, pos = 0, zer = 0;
    char z;

    do {
        cout << "Input another positive/negative number or 'x' to stop\n";
        cin >> input;
        cin.ignore();

        if (input > 0){
            pos++;
        } else if (input == 0){
            zer++;
        } else if(input < 0){
            neg++;
        }
    } while (z!='x');

    cout << "You entered " << pos << " positive numbers.\n";
    cout << "You entered " << neg << " negative numbers.\n";
    cout << "You entered " << zer << "Zeros.";

    return 0;
}


推荐答案

获取数字直到用户输入别的东西:

By far the simplest way of getting numbers until a user enters something else is this:

int input = 0;
cout << "Input a positive/negative number or 'x' to stop\n";
while(cin >> input) {
    //they entered a number, do stuff    
    if (input > 0)
        pos++;
    else if (input == 0)
        zer++;
    else if (input < 0)
        neg++;

    cout << "Input another positive/negative number or 'x' to stop\n";
}
//cin failed to read a number, probably because they entered a letter
//if they failed to enter a number, we need to clear the fail flag before we can use cin again
cin.setstate(cin.rdstate()&~std::ios_base::failbit); 

cout << "You entered " << pos << " positive numbers.\n";
cout << "You entered " << neg << " negative numbers.\n";
cout << "You entered " << zer << "Zeros.";

我不会推荐任何更复杂的,直到你得到非常高级的C ++。解析输入是非常难以正确地,很多经验丰富的人错误。

I wouldn't recommend anything more complicated until you get very advanced with C++. Parsing input is immensely difficult to get correctly, and many experienced people get it wrong.

这篇关于让用户给出输入,直到他输入X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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