【发布时间】:2021-07-25 06:38:49
【问题描述】:
我对 c++ 很陌生,当为变量 cont 输入字符串并回答时,我试图让我的程序退出循环时遇到问题。在 python 中,做简单的检查很容易,但我不确定我应该在 cpp 中做什么。我尝试使用if(typeid(answer)) == typeid(string)) 进行检查,但这不起作用。我没试过检查
'y'||'Y'||'n'||'N' 继续,但我假设它会是这样的?只检查这 4 个字符?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main() {
unsigned seed;
char cont = 'y';
int answer = 0;
seed = time(nullptr);
srand(seed);
rand() % 100 + 1;
cout << "Lets play a math game!\n";
while(cont == 'y')
{
int num1 = rand() % 100 + 1;
int num2 = rand() % 100 + 1;
cout << "What is the result of this addition? \n " << num1 << '\n' << "+" << num2 << endl;
cin >> answer;
if (typeid(answer)==typeid(string))
{
while(typeid(answer) == typeid(string))
{
cout << "Please enter an integer!" << endl;
cin >> answer;
}
}
else if (typeid(answer) == typeid(int)) {
if (answer == (num1 + num2)) {
cout << "You are correct, would you like to play again?" << endl;
cin >> cont;
} else {
cout << "You were incorrect, would you like to try again? enter y/n" << endl;
cin >> cont;
}
} else {
answer = 0;
cout << "You did not enter an integer!\n" << endl;
cout << "Would you like to try again?" << endl;
}
}
return 0;
}
【问题讨论】:
-
int answer = 0;始终是int,而不是string。您可以在if中检查变量是否属于某种类型,但这不是您真正需要的 -
if(inRange(0,200,answer)) 之类的东西会起作用吗?输入字符时会发生什么?字符是否包含一些整数值
-
在 Python 中,您读取一个字符串并将其转换为一个数字,例如
int(input())。在 C++ 中,这是通过int answer; cin >> answer;一步完成的。您必须检查cin的状态以查看读取和转换是否成功。如果失败,则设置错误位。见en.cppreference.com/w/cpp/io/ios_base/iostate。或者你可以像在 Python 中一样做。将其读入字符串并转换:std::string answer; cin >> answer; std::stoi(answer);
标签: c++ loops while-loop