#include <iostream>
#include <string>
using namespace std;
int main ()
{
do
{
string name, answer;
cout << "Welcome to the prime number checker! Please enter your name: ";
getline (cin, name);
int a;
cout << "\nHello " << name;
cout << "\nPlease enter an integer: ";
cin >> a;
cin.sync();
if (a == 2)
{
cout << "\nThis is a prime number" << endl;
}
else
{
for (int b = 2; b < a; b++)
{
if (a % b == 0)
{
cout << "This number is not prime number" << endl;
break;
}
else
{
cout << "This number is a prime number." << endl;
break;
}
}
}
cout << "Do you want to do this again (Yes or No)?";
getline (cin, answer);
}
while (answer == "yes" || answer == "YES" || answer == "Yes"); //Not declared in this scope
return 0;
}
答案 0 :(得分:2)
您在DOM
块中声明了answer
。但是,然后尝试在该范围块之外引用do
。
在answer
的顶部而不是answer
块中声明main
。
答案 1 :(得分:2)
您需要在循环外移动answer
的声明:
string answer;
do {
string name;
...
} while (answer == "yes" || answer == "YES" || answer == "Yes");
如果在循环中声明它,则在评估while
子句时它不再存在。
答案 2 :(得分:0)
正如其他人所说,“回答”变量只存在于循环内部 - 它无法从外部访问。
另一个建议:不是检查每个可能的大写排列,而是将整个字符串强制转换为小写。 (你实际上错过了几个 - 总共有6个因为每个职位可能有两个可能的值之一。例如,大概应该像“YeS”这样的东西仍然被接受为“是”)。