如果用户将字母作为输入,则重新进入年龄
Re-enter the age if the user put a letter as an input
我们的教授告诉我们创建一个函数,如果用户输入年龄的信件,则该功能将使用户再次重新进入年龄。但是,只有年龄才能更新而不会再次输入名称,我尝试了,但这是我的代码。
#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
返回
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");
相关文章:
- 如何在输入新内容 c++ 之前删除文件中的所有内容
- 从子菜单返回后,正确的输入至少进入验证循环一次
- 静态堆栈函数不会 1) 输入第一个元素 2)添加新元素时识别旧元素
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- 如何在C++中将构造函数的新输入推回构造函数的默认输入?
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 如何在C++中创建总是在循环中接受新输入的独立进程
- 用C++计算输入文本的新行数
- 实现一个函数,该函数将字符串作为输入并返回一个新字符串,辅音字母不替换为 "!"
- 为什么当测试用例数为 1 时,我的程序不输入而是打印新行?
- 将新的 cv::mat 输入vx_graph
- 有没有办法从程序中打开一个新控制台,然后进入其中
- 如何让输入文件进入数组
- 如何创建一个C ++函数,该函数在每次用户输入新数据时创建新对象
- 为什么输入文件中的数字没有进入我的数组 c++?
- 以编程方式输入新行
- C++:进入循环后增加新行
- 程序永远不会进入我可以输入信息的部分
- C++ 从现有输入变量到文件的新输入
- cin.有限制地忽略,继续丢弃新的输入