字母输入运行无限循环



我写了一个函数来解释数字,并尝试涵盖所有输入的可能性。

总的来说,它适用于数字输入,但是当我输入字母输入时,它会在屏幕上开始无限循环打印语句。众所周知,在计算机内部,像"A或a或b或B"等单个字符由整数表示,正如我从老师那里学到的那样,我们可以将单个字符存储到具有整数数据类型的变量中。我不是在谈论字符串,这意味着字符的集合。该程序会产生单个字符的问题!

#include <iostream>
#include <string>
using namespace std;
void squire();
int main() {
squire();
}
void squire() {
double num = 1.0, pow = 1.0, Squire_Number = 1.0;
char ans;
reStart:
cout << "please Enter the Number: n";
cin >> num;
cout << "please enter the nmber you want to power the number with: n";
cin >> pow;
if (num > 0 && pow>0) {
for (int i = 1; i <= pow; i++) {
Squire_Number *= num;
}
cout << pow << " power of " << num << " is equil to : " << Squire_Number;
goto option;
}
else
{
cout << "Please enter Positve Integers. n" ;
option:
cout<< "nPease type 'Y' to Enter the values again OR type 'c' to Exit ! n";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
goto reStart;
} else if (ans == 'c' || ans == 'C') {
cout << "thank you for using our function. n";
}
}
return;
}

最好尝试读取 std::string 中的输入,然后解析字符串以检查是否只有数字字符,然后使用 std::atoi 将字符串转换为整数。最后一个建议,避免使用 goto 指令,这种做法会使代码难以阅读。

#include <iostream>
#include <string>
#include <cstdlib>
bool OnlyNumeric(const std::string& numStr)
{
size_t  len= numStr.length();
int i;
for (i=0;i<len && numStr[i]  <='9' && numStr[i]  >='0';i++) ;
return i == len;
}

int main()
{
std::string inputStr;
int num;
do{
std::cout  << "Input number:n";
std::cin >> inputStr;
}   
while (!(OnlyNumeric(inputStr)  && (num=std::atoi(inputStr.c_str())) ));

std::cout  << "Your number is : " << num;
return 0;
}

最新更新