C ++循环用户输入直到正确 [英] C++ Looping user input until correct

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

问题描述

我要用户输入0到127之间的值,如果他们没有输入正确的值,我希望程序继续询问他们,直到他们输入正确的值.

I am asking the user for input in the range of 0 - 127, if they don't put the correct value I want the program to keep asking them until they input a correct value.

目前,我在一个类中有以下代码:

At the moment I have the following code in a class:

void setNoteNumber (int value)
{

    number = value;

    while (value < 0 || value > 127) {

    std::cout << "This number is not in the range of 0 - 127, please select a new value: ";

    }
}     

这是可行的,除了他们输入错误的值外,我的控制台还会反复显示错误消息.如果有人可以帮助我,将不胜感激!

It kind of works, apart from if they input the wrong value my console repeatedly displays the error message. If anyone can help me it would be greatly appreciated!

谢谢!

推荐答案

当前程序设计错误, value 在while循环中没有变化,因此它是无限的.这样的事情可能会更好:

The program design is currently wrong, value doesn't change in the while loop, so it is infinite. Something like this might work better:

bool setNoteNumber(int value); //return false if value is outside range
//main loop
do {
    value = getInput();
} while(setNoteNumber(value))

这篇关于C ++循环用户输入直到正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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