gpt4 book ai didi

c++ - 字母输入运行无限循环

转载 作者:太空狗 更新时间:2023-10-29 22:53:57 34 4
gpt4 key购买 nike

我编写了一个函数来获取数字并尝试涵盖所有输入可能性。

总的来说,它在数字输入时工作正常,但当我输入字母输入时,它会在屏幕上开始无限循环打印语句。我们都知道在计算机内部的单个字符,如“A or a or b or 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;
}

关于c++ - 字母输入运行无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58087469/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com