字母输入运行无限循环
alphabetic inputs run infinite loop
我写了一个函数来解释数字,并尝试涵盖所有输入的可能性。
总的来说,它适用于数字输入,但是当我输入字母输入时,它会在屏幕上开始无限循环打印语句。众所周知,在计算机内部,像"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;
}
相关文章:
- 过载'operator new'如何导致无限循环?
- 运行无限循环的最小二叉树问题
- 作为无限循环运行
- 字母输入运行无限循环
- 插入无限循环运行的单向链表
- 由于next_permute而运行无限循环
- boost::thread应该在无限循环中运行,并等待没有互斥锁的新输入
- 从C++应用程序运行批处理脚本,并检查它是否具有无限循环
- 代码在小输入时运行良好,但在大输入时就像一个无限循环
- 我认为做而正在进入无限循环.或数组.(运行时错误)
- 日历运行无限循环
- 终止一个在无限循环中运行的std::线程
- 如何运行一个无限循环
- 使用两个线程运行和中断一个无限循环
- 来自cmath的函数生成运行时无限循环(没有这样的文件或目录)
- 为什么我得到无限循环只有线程# 0后,所有5个线程运行多线程c++用餐哲学家谜语
- 我总是在运行这个程序时陷入无限循环
- 当主线程在无限循环中运行时,用QTcpSocket::write写入的字节没有被服务器接收
- c++:程序在运行函数时进入无限循环
- 如何在无限循环中运行线程