gpt4 book ai didi

c++ - 我想我试图在我的变量中传递错误的数据?里面的新手coder

转载 作者:行者123 更新时间:2023-11-30 01:58:46 24 4
gpt4 key购买 nike

我开始学习 C++ 的一些基础知识,我想编写一些代码来实践我所学的知识。我想做一个类和一些功能。应该是开始文字游戏的标题画面,除了没有游戏……还没有:P

每当我输入 1 开始时,它会显示“Good Work”,在我按下回车键后它什么也不做。

任何方向正确的点都会很棒。我一直在观看有关功能的视频和阅读教程,它似乎没有涵盖我遇到的问题...

#include <iostream>
#include <string>


using namespace std;

//Function Protos
void keyError();
int userInput(int x);

//class library
class Title
{
bool nSelect;
int x;
public:
void titleScreen()
{
while(nSelect)
{
cout << "Welcome to Biggs RPG!" << endl << "1. Play 2. Exit" << endl;
userInput(x);
if (userInput(1))
nSelect = 0;
else if (userInput(2))
{
cout << "Closing program..." <<endl;
nSelect = 0;
}
else
keyError();
}
}
};

int main()
{
Title displayTitle;
displayTitle.titleScreen();

cout << "Good work";
return 0;
}

void keyError()
{
cout << "Meow? Wrong input try again." << endl;
}

int userInput(int x)
{
x = 0;
cin >> x;
return x;
}

最佳答案

存在许多文体和技术问题。尝试从 The Definitive C++ Book Guide and List 中推荐的资源中学习.

这是一个开始......

#include <iostream>
#include <string>

// "using namespace std;" is poor practice. Better to write out std::

/* Unless you will have two title screens at the same time,
this should probably be a namespace, not a "singleton" class. */
namespace Title
{
int nSelect;

void titleScreen()
{
do {
// prompt for input
std::cout << "Welcome to Biggs RPG!\n" "1. Play 2. Exit\n";

// get ready to accept input, even if there was an error before
if ( ! std::cin ) {
std::cin.clear(); // tell iostream we're recovering from an error
std::cin.ignore( 1000, '\n' ); // ignore error-causing input
}
// repeat if invalid input
} while( ! std::cin >> nSelect || ! handleInput( nSelect ) );

不同之处在于您要请求输入,然后处理它。您发布的代码每次检查输入内容时都会再次请求输入

这是一个do … while 循环,因此它至少执行一次,然后只要条件末尾 为真就会重复执行。如果用户输入无效,则 ! std::cin 的计算结果为 true。然后 C++ 的策略是停止返回任何输入,直到您调用 std::cin.clear(),这表明您将再次尝试。 ignore 然后删除无效输入。然后! std::cin >> nSelect 尝试读取一个数字,如果该操作成功,则调用 handleInput(您必须编写),它应该返回 false如果输入无效。因此,如果读取数字失败,或者输入了错误的数字,循环将再次进行。

关于c++ - 我想我试图在我的变量中传递错误的数据?里面的新手coder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16868475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com