模拟检查,检查用户输入的数量时出错。 C ++

时间:2015-03-04 23:52:58

标签: c++ c-strings string-conversion

我写了一个打印出模拟薪水的程序。根据我老师的标准,一切都没问题,除了我的循环检查用户输入的金额。

我得到用户输入的金额并将其放入字符串中。然后我将其转换为int以检查它是否在0 - 10,000的范围内。它要么完全跳过检查,要么程序崩溃。知道为什么吗?它位于getInfo函数中。我必须把金额作为一个字符串。我最终也必须使用字符串类对象。

void getInfo(int nameS, int dateS, int amountS, char name[],char date[],  char check[])
{
cout<< "Please enter the name of the recipient: ";
cin.getline(name, nameS);

cout<< "Please enter the date EX. mm/dd/yy: ";
cin.getline(date, dateS);
 do
 {
    if(strlen(date)!= 8)
    {
        cout<< "That was not the correct date format. Please Enter again. Ex. mm/dd/yy";
        cin.getline(date, dateS);
    }

 } while(strlen(date)!= 8);
    // Small check for the right size. Does not check for character.

cout<< "Please enter the amount: above zero and under 10,000: ";
cin.getline(check, amountS);
double quickCheck=atof(check);

//PROBLEM
    do{
            if(quickCheck>10,000 || quickCheck<0)
            {
                cout<<"That amount is not within the bounds. Please enter again.";
                cin.getline(check,amountS);
            }
      } while(atoi(check)>10,000 || atoi(check)<0);

    return;
 }

1 个答案:

答案 0 :(得分:0)

在没有实际运行所有代码的情况下,我能看到的唯一问题是当您在检查中编写10,000时 - 我不相信c ++会接受数字中的逗号。请改为10000

此外,您需要将quickCheck重新分配给末尾while循环内新输入的值(否则检查只使用第一个值)。

最后 - 你有没有理由进行双重检查和整数检查(atofatoi)?

<强> ADDITION

另外,当您更加严格地检查用户输入时,请查看stringstream。您需要将输入的string加载到stringstream,然后将其发送到int(或double,具体取决于用户应提供的数据类型)然后将其发送回stringstream然后再发送到另一个string - 如果最终string与原始{{1}}相同,则输入是正确的类型,以便您可以进行范围检查,如果它们不一样那么用户就会写出类似“hello bob”之类的东西,例如你期待像“10.4”这样的东西(我班上的一位帮手非常高兴地通过击中中间部分向我介绍键盘,然后按Enter键,看着我的程序疯狂...)

相关问题