c++ - 控制台将继续关闭而不是读取 if 语句中的字符串

标签 c++

我想做的是让玩家“选择”他们想成为的职业,每个职业都有一个编号。不同的数字将在控制台中打印出不同的字符串,我想通过制作 if 语句来做到这一点。换句话说,玩家将输入一个选择,他们的选择最终将打印出不同的 if 语句。但是,每次我运行代码时,程序都会在询问用户他们想要使用哪个类时结束,而不会打印出该类的消息。

#include "stdafx.h"
#include<iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;


int main()
{
    int Name,Class;
    cout << "Welcome to the world of Jumanji!\n\n";
    cout << "Please Tell me your name:";
    cin >> Name;
    cout << "\n\nOkay, so your name is " << Name << "? Welcome to the world of Jumanji - A game for those who seek to find a way to leave their world behind\n\n";
    cout << "I am a fellow adventurer who will aid you during your journey\n\n";
    cout << "Alright " << Name << "I need you to tell me what you will be playing as\n\n";
    cout << "1.Archaeologist\n2.Cartographer\n3.Commando\n4.Pilot\n5.Zoologist ";
    cin >> Class;

    if (Class == 1) {
        cout << "Are you sure that you want to be a Archaeologist?";
        system("pause");
    }
    else if (Class == 2) {
        cout << "Are you sure that you want to be a Cartographer?";
        system("pause");
    }
    else if (Class == 3) {
        cout << "Are you sure that you want to be a Commando?";
        system("pause");
    }
    else if (Class == 4) {
        cout << "Are you sure that you want to be a Pilot?";
        system("pause");
    }
    else if (Class == 5) {
        cout << "Are you sure that you want to be a Zoologist?";
        system("pause");
    }
    return 0;
}

我做错了什么?

最佳答案

因此,名称应该是string,而不是int

string Name;
int Class;

因为用户可能输入“John Doe”作为名字,cin >> Name; 只会得到“John”,而将“Doe”留在缓冲区中,缓冲区现在结束于Class,导致 Class 包含任意值。因此 if else 不起作用。使用 getline() 应该可以解决问题。

string Name;
int Class;
cout << "Welcome to the world of Jumanji!\n\n";
cout << "Please Tell me your name:";
getline(cin, Name);

关于c++ - 控制台将继续关闭而不是读取 if 语句中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353303/

相关文章:

c++ - Visual C++ 资源文件符号

c++ - 将 C++ 常量暴露给虚幻中的蓝图

c++ - 将 ICU UnicodeString 转换为平台相关的 char *(或 std::string)

STL - 将 istream 中的一行单词转换为 vector 的最简单方法?

c++ - 使用 mex : Matlab crashes 将大矩阵从 Matlab 传递到 C

c++ - MSVC 处理大量包含路径

c++ - 如何修改运行时加载的 DLL 的导入地址表

c++ - c++ 中的多态性与模板化类

c++ - 使用 boost.python 从 C++ 将变量导出到 python

c++ - 为什么 + 运算符重载返回类型是类类型而不是整数?