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


版权声明:本文为Edwardsino原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。