字母输入导致无限循环

3

我写了一个函数来计算数字的平方并试图包含所有可能的输入。

总体上,它与数字输入一起运行良好,但当我输入字母时,它会在屏幕上启动无限循环打印语句。我们都知道,在计算机内部,单个字符,例如"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;
  }

当我输入字母值作为num或pow,或者两者都是时,我将它们声明为双精度数据类型。如果出现以上情况,就会开始一个无限循环。而对于char数据类型,我只是用来从用户那里获取答案。 - LIAQAT ALI
1
附注:for (int i = 1; i <= pow; i++)for (int i = 0; i < pow; i++)相同,只是更多的人会觉得它很奇怪,并且会想知道你是否有一个偏移一的错误。 - user4581301
小心使用“goto”。它很难正确使用,甚至更难向同事证明其使用的必要性。通常当人们看到涉及“goto”语句的错误时,他们的反应是“不要使用goto”,而没有实际帮助来修复错误。因为“goto”通常会成为错误的根源。虽然在这种情况下它不是问题所在,但我还没有深入探索代码,无法告诉您是否存在其他错误。 - user4581301
请参考 std::toupperstd::tolower。这将简化您的 if 语句,例如:if (toupper(ans) == 'Y') - Thomas Matthews
非常感谢大家宝贵的评论和建议。但我们都知道,在计算机内部,像“A”、“a”、“b”、“B”等单个字符都是用整数表示的。我从老师那里学到,我们可以使用int数据类型将单个字符存储到变量中,这里我不是在谈论字符集合,也就是字符串。这个程序在处理单个字符时出现了问题! - LIAQAT ALI
显示剩余7条评论
1个回答

1
最好尝试读取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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接