While循环中的If循环中的While循环

While loop in a If loop in a while loop

本文关键字:循环 While If      更新时间:2023-10-16

在下面的代码中,我遇到了这个问题,当我第一次运行它时,它工作得很好,但是在随后的循环中,当我选择选项1时,没有任何显示只是回到"菜单",它只在第一次工作,之后没有时间,有人能解释这个问题吗?

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    int choice=0;
    while(choice != 2){
        cout << "(1)Create" << endl;
        cout << "(2)Exit" << endl;
        cin >> choice;
        if(choice == 1){
            int choice2;
            while(choice2 != 7){
                cout << "You chose one " << endl;
                cin >> choice2;
            }
        }
    }
}

我不明白你的问题,但这对我来说很好…(实际上是相同的代码,只是更整洁)。

int main()
{   
int choice = 0;
    while (choice != 2)
    {
        std::cout << "(1)Create" << std::endl;
        std::cout << "(2)Exit" << std::endl;
        std::cin >> choice;
        if (choice == 1)
        {
            int choice2 = 0;
            while (choice2 != 7)
            {
                std::cout << "You chose one " << std::endl;
                std::cin >> choice2;
            }
        }
    }
    return 0;
}

问题可能是,您没有在声明后初始化choice2变量,这意味着它包含垃圾值