我使用 Visual Studio Community 2017 进行 C++ 编程。我有以下代码。在这里,do while 循环运行了几次并且不会因为询问输入它应该在哪里而停止。但是,在最后一个 switch case 程序中,如果我输入 1 而不是 n,程序运行良好。请帮忙!!!
// Welcome2018.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<bitset>
using namespace std;
int main()
{
string month[] = { "January", "February", "March", "April", "May", "June", "July", "August" "September", "October", "November", "December" };
int m, d, answer;
cout << "Welcome 2018!!!" << endl;
do
{
cout << "Enter the number corresponding to the month you want displayed" << endl;
cin >> m;
switch (m)
{
case 1:
cout << month[0] << endl;
cout << "Enter the date to know the day it is/will be" << endl;
cin >> d;
if (d == 7 || d == 14 || d == 21 || d == 28)
{
cout << "The day on " << d << " January is Sunday!" << endl;
}
else if (d == 1 || d == 8 || d == 15 || d == 22 || d == 29)
{
cout << "The day on " << d << " January is Monday!" << endl;
}
else if (d == 2 || d == 9 || d == 16 || d == 23 || d == 30)
{
cout << "The day on " << d << " January is Tuesday!" << endl;
}
else if (d == 3 || d == 10 || d == 17 || d == 24 || d == 31)
{
cout << "The day on " << d << " January is Wednesday!" << endl;
}
else if (d == 4 || d == 11 || d == 18 || d == 25)
{
cout << "The day on " << d << " January is Thursday!" << endl;
}
else if (d == 5 || d == 12 || d == 19 || d == 26)
{
cout << "The day on " << d << " January is Friday!" << endl;
}
else if (d == 6 || d == 13 || d == 20 || d == 27)
{
cout << "The day on " << d << " January is Saturday!" << endl;
}
}
cout << "Are you sure you want to quit?" << endl;
cout << "Enter Y/N based on your choice:";
cin >> answer;
switch (answer)
{
case 1:
answer = 1;
case 'n':
answer = 1;
default:
answer = 2;
}
} while (answer = 1);
cout << "Thank You and Come Again!!!" << endl;
return 0;
}
最佳答案
您的代码存在一些问题:
一个。在最后一个 while 语句中,您应该使用检查相等性的“==”运算符,而不是执行赋值的“=”运算符。
while (answer == 1)
在最后一个 switch case 中,你应该在每个 case 的末尾添加一个 break 命令。否则,它也会自动执行默认选项下的代码块。
switch (answer)
{
case 1:
answer = 1;
break;
case 'n':
answer = 1;
break;
default:
answer = 2;
break;
}
第一个 switch-case block 目前只包含一个 case。因此,它并不是真正需要的。
关于c++ - 为什么我的 do 循环运行了几次并且不要求输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48074359/