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

Re-enter the age if the user put a letter as an input

本文关键字:新进入 输入 用户 如果      更新时间:2023-10-16

我们的教授告诉我们创建一个函数,如果用户输入年龄的信件,则该功能将使用户再次重新进入年龄。但是,只有年龄才能更新而不会再次输入名称,我尝试了,但这是我的代码。

#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;
}

除非您要返回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;
    }
 }

在丢弃不良输入时获得数字比我想要的更麻烦。这是一种一般方法:

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");