如果用户将字母作为输入,则重新输入年龄

时间:2014-03-12 14:44:43

标签: c++

我们的教授告诉我们创建一个功能,如果用户输入年龄字母,它将让用户再次重新进入年龄。但是,只有年龄会更新而不再输入名称, 我试过了,但这是我的代码。

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;
string inputName, inputGender, inputBirthday;
int inputAge, inputChoice;
ofstream fileOutput("Example.txt");
int getAge() {
    cin>>inputAge;
    if (inputAge <= 50) {
        fileOutput<<inputAge<<endl;
    } else {
        cout<<"Error: Re-enter your age: ";
        cin>>inputChoice;
        getAge();
    }
}

int main() {
    cout<<"Enter your Name:     ";
    getline(cin, inputName);
    fileOutput<<inputName<<endl;
    cout<<"Enter your Age:      ";
    getAge();
    cout<<"Enter your Gender:   ";
    getline(cin, inputGender);
    fileOutput<<inputGender<<endl;
    cout<<"Enter your Birthday: ";
    getline(cin, inputBirthday);
    fileOutput<<inputBirthday<<endl;
    fileOutput.close();
    cout<<"Done!\n";
    system("PAUSE");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

除非你要返回一个int,否则用int返回来声明getAge是没有意义的

void getAge()
{
    std::string line;
    int i;
    while (std::getline(std::cin, line))
    {
        std::stringstream ss(line);
        if (ss >> i)
        {
           if (ss.eof())
           {
              break;
           }
        }
        std::cout << "Please re-enter the age as an integer" << std::endl;
    }
    if (i <= 50)
    {
       fileOutput << i <<endl;
    }
 }

答案 1 :(得分:0)

在丢弃错误输入的同时获取数字比我想要的更麻烦。这是一般方法:

template <typename T>
T get_on_line(std::istream& is, const std::string& retry_msg)
{
    std::string line;
    while (std::getline(std::cin, line))
    {
        std::istringstream iss(line);
        T x;
        char c;
        if (iss >> x)
            if (iss >> c)
                throw std::runtime_error("unexpected trailing garbage on line");
            else
                return x;
        else
            std::cerr << retry_msg << '\n';
    }
}

用法:

int num = get_on_line<int>(std::cin, "unable to parse age from line, please type it again");