我正在制作一个数字猜测游戏,要求用户输入一个四位数。然而,用户可能输入少于或多于四位数字和/或非整数输入(即无效输入)。我的代码将用户输入存储到一个整数类型的数组中。我现在才意识到,我的代码仍然会将"无效输入"识别为有效,因为存储输入的数组被声明为整数类型。以下是我代码的一部分:
#include <iostream>
using namespace std;
void guess(int num_guess[], int size);
int main(){
int list[4];
guess(list, 4);
for(int i = 0; i < 4; i++){
cout << list[i];
}
cout << endl;
}
void guess(int num_guess[], int size){
int number;
cin >> number;
for(int i = size-1; i >= 0; i--){
num_guess[i] = number%10;
number /= 10;
}
}
cout << list[i];
并不是原始代码的一部分,但这就是我发现无效输入仍然被接受的原因。我以前在Python中制作rationalroots计算器程序时遇到过类似的问题,但那时检测和排除不需要的输入要容易得多。我的问题是,如何修复我的代码,使其能够检测到无效输入并输出类似"无效输入"的内容,然后继续向用户请求另一个输入。
以下是一个用于检查string
是否为4位正整数的函数。如果这个数字可能是负数,你只需要检查一下s[0] == '-'
。
bool check(string &s){
if(s.size() != 4) return false;
for(int i=0; i < 4; i++){
if(s[i] < '0' || s[i] > '9') return false;
}
return true;
}
以下是将string
转换为int
:的函数
#include <stringstream>
int strToInt(string &s){
stringstream ss(s);
int ans;
ss >> ans;
return ans;
}
要排除非整数输入,请尝试以下操作:
void skip_to_int(){
// if is not an integer
if(cin.fail()){
// check character type
cin.clear();
char ch;
while(cin>>ch){
// throw away non digits
if(isdigit(ch)){
// put back if digit to be written
cin.unget();
return;}
}
}
else error ("no input");
}
您的输入提示功能将如下所示:
cout << "Please enter an integer" << endl;
int n=0;
if(cin>>n){
// integer OK, proceed
}
else{
cout << "That was not a numeric value, try again." << endl;
skip_to_int();}
这是我的解决方案。小心,它使用C++11。如果您使用std::stringstream
,当然没有必要,但这应该可以很好地工作。
我想你不想要负数。我还假设前面任何0的数字都不会使这个数字成为4位数。它将截断填充的0,所以01234是一个4位数的数字,但0123不是。
void guess(int num_guess[], int size)
{
int number;
// if the length of the number isn't 4, try again until it is
do {
std::cin >> number;
if(std::to_string(number).length() != size)
std::cout << "You messed up the input. How hard could it be? Try again..." << std::endl;
} while(std::to_string(number).length() != size);
// by now, the size is definitely 4. insert it by digit into num_guess
for(int i = size-1; i >= 0; i++) {
num_guess[i] = number%10;
number /= 10;
}
}
#include <iostream>
#include <limits>
int main() {
int i = 0;
std::cout << "Please enter a number with four digits: ";
while( !(std::cin >> i) || !(i / 1000.0f >= 1.0f) )
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cout << "Invalid entry." << std::endl;
std::cout << "Please enter a number with four digits: ";
}
}
std::cin.clear()清除当前流结构上的所有错误标志,std::cin.ignore()清除输入流本身。一旦我们在这个操作之前不知道流的大小,我就使用流大小的最大可能值来确保任何流长度都可以被清除。
添加#include"math.h"
并更改猜测
void guess(int num_guess[], int size){
int number = 0;
bool firstTime = true;
do
{
if (!firstTime)
cout << " Error, try again " << endl;
firstTime = false;
cin >> number;
} while (number<pow(10, size-1) || number>=pow(10, size));
for(int i = size-1; i >= 0; i--){
num_guess[i] = number%10;
number /= 10;
}
}