cin输入错误解决方案

这篇博客介绍了如何在C++中编写一个函数,用于处理用户输入时遇到的非法字符,如'aaa', '1a', '1.27'等。函数名为`cin_int`,当检测到非法输入时,它会清除输入流,提示用户重新输入一个数字,以确保输入的正确性。在`main`函数中,该函数被用于获取用户输入的整数`today`。
摘要由CSDN通过智能技术生成

定义输入应该为int,而实际输入为aaa,1a,1.27等等非法字符时的解决方案。

文件名称为 "cin_int.cpp" :

#include <iostream>

#include <string>

/*

*函数名称:cin限制输入函数

*作用:定义输入应该为int,而实际输入为aaa,1a,1.27等等非法字符时,警告输入为非法字符,并提示重新输入。

*参数:参数1(const std::string& str):一个用来提示输入的字符串。

            参数2( auto& number):自定义的输入变量。

*返回值:无(void)

*备注:auto可改为int,会减少对其它数据的兼容,如浮点型数据

*/

void cin_int(const std::string& str, auto& number)

{

top:

std::cout << str;

while (!(std::cin >> number))

{

std::cin.clear();

while (std::cin.get() != '\n')

continue;

std::cout << "\b(警告:输入非法字符,请重新输入一个数字!)" << std::endl;

std::cout << str;

}

if (std::cin.get() != '\n')

{

std::cin.clear();

while (std::cin.get() != '\n')

continue;

std::cout << "\b(警告:输入非法字符,请重新输入一个数字!)" << std::endl;

goto top;

}

}

在main函数中使用这个函数:

int today;

cin_int("今天星期几:",today);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值