控制台将继续关闭,而不是读取 if 语句中的字符串
Console will keep closing out instead of reading the string within the if statements
我想做的是让玩家"选择"他们想要的职业,每个职业都有一个数字。不同的数字会将不同的字符串打印到控制台中,我想通过制作 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);
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++如何正确实现并行IF流读取
- 使用"IF" C++逐行读取文本文件
- C# 读取完全锁定的文本文件或读取 if 语句外部的输出
- 控制台将继续关闭,而不是读取 if 语句中的字符串
- 不会让我在 IF 语句(家庭作业)之后读取用户输入
- c++ 读取左 IF 语句条件和右语句条件
- C++ if 语句不起作用(不会读取内存)
- 简单的c++文件读取使用if流
- c++从文件中读取:使用.fail()或try/catch的if条件
- for 循环的问题,它同时读取 if 和 else if 语句
- c++ if命令读取为真,尽管为假
- c++不读取IF/Else语句