cin输入错误解决方案

定义输入应该为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);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值