用c ++输入验证。 [英] Input validation in c++.

查看:68
本文介绍了用c ++输入验证。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码,程序正常工作,直到我输入除数字以外的任何内容。在分数的输入验证期间出现问题。

  #include   <   iostream  >  
#include < < span class =code-leadattribute> iomanip >
使用 namespace std;

int main()
{
int counter = 0 ;
double 得分,
averagescore,
totalscore = 0 。< span class =code-digit> 0 ;

cout<< 输入学生的分数,如果没有剩下的学生,则输入-1。\\ n ;
cin>>得分了;
while (得分< - 1 ||得分> 100
{
cout<< \ n这不是一个有效的答案,请输入介于-1和100之间的百分比 ;
cin>>得分了;
}

while (得分!= - 1
{
totalscore + =得分;
cout<< \ n输入学生的分数,如果没有剩下的学生,则为-1。\ n;
cin>>得分了;
while (得分< - 1 ||得分> 100
{
cout<< \ n这不是一个有效的答案,请输入介于-1和100之间的百分比 ;
cin>>得分了;
}
counter ++;
}

averagescore = totalscore / counter;
cout<< \ n该课程的平均分为:<< averagescore<< ' %'<< ENDL;
}





我的尝试:



我试着查看是否有任何逻辑错误,即使我多次查看也没有找到我。我假设这是一个逻辑错误,但我不知道该怎么做才能使它输入验证只接受介于-1和100之间的数字。

解决方案

< blockquote>请参阅:讲义 - cin.fail(),cin.clear(),cin.eof ()和strchr() [ ^ ] - 使用 cin.fail 检查用户是否输入了有效数字,或者例如单词Hello。


Below is my code and the program works fine until I enter anything other than a number. The problem occurs during the input validation of score.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int counter = 0;
    double score,
           averagescore,
           totalscore = 0.0;

    cout << "Enter the score of a student, or -1 if no more students are left.\n";
    cin >> score;
    while (score < -1 || score > 100)
    {
        cout << "\nThat is not a valid answer please enter a percent between -1 and 100\n";
        cin >> score;
    }

    while (score != -1)
    {
        totalscore += score;
        cout << "\nEnter the score of a student, or -1 if no more students are left.\n";
        cin >> score;
        while (score < -1 || score > 100)
        {
            cout << "\nThat is not a valid answer please enter a percent between -1 and 100\n";
            cin >> score;
        }
        counter++;
    }

    averagescore = totalscore / counter;
    cout << "\nThe average score of the class is: " << averagescore << '%' << endl;
}



What I have tried:

I tried looking through to see if there were any logic errors and none came to me even though I looked through several times. I'm assuming this is a logic error, but I am not sure what I should do to make it so this input validation only accepts numbers between -1 and 100.

解决方案

See here: Lecture Notes - cin.fail(), cin.clear(), cin.eof() and strchr()[^] - use cin.fail to check if the user entered a valid number at all, or the word "Hello" for example.


这篇关于用c ++输入验证。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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