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

Console will keep closing out instead of reading the string within the if statements

本文关键字:if 读取 语句 字符串 继续 控制台      更新时间:2023-10-16

我想做的是让玩家"选择"他们想要的职业,每个职业都有一个数字。不同的数字会将不同的字符串打印到控制台中,我想通过制作 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!nn";
cout << "Please Tell me your name:";
cin >> Name;
cout << "nnOkay, 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 behindnn";
cout << "I am a fellow adventurer who will aid you during your journeynn";
cout << "Alright " << Name << "I need you to tell me what you will be playing asnn";
cout << "1.Archaeologistn2.Cartographern3.Commandon4.Pilotn5.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!nn";
cout << "Please Tell me your name:";
getline(cin, Name);