gpt4 book ai didi

多次打印 C++ 消息

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:47 25 4
gpt4 key购买 nike

我正在学习 C++,但我有一个问题无法解决。当我键入 X 个字符时,当前字符数将导致“失败”消息显示 X 次。

截图,

enter image description here

这是我的代码,

#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <ctype.h>

using namespace std;

int generateNumber()
{

int randomNumber;

srand(time(0));
randomNumber = rand() % 100 + 1;

return randomNumber;

}

int main()
{

// Predefine vars
int lifes = 5;
int attempts = 0;
int randomNumber = generateNumber();
int gameStarted = 0;
int gussedNumber;
int score = 0;
string username;

cout << "--------------------------------" << endl;
cout << "------- GUESS THE NUMBER -------" << endl;
cout << "---------- VERSION 1.0 ---------" << endl;
cout << "--------------------------------" << endl << endl;

while(gameStarted == 0)
{
cout << "Enter your username before we get started" << endl;
cin >> username;
gameStarted = 1;
system("cls");
}

if(gameStarted == 1)
{

cout << "Welcome, " << username << "!" << endl;
cout << "Guess a number between 1 - 100" << endl << endl;

while(attempts <= lifes)
{

// If you dont have any more lifes left
if(lifes == 0)
{

system("CLS");
cout << "Game Over" << endl;
cout << "Lets try again." << endl;
cout << "Guess a number between 1 - 100" << endl << endl;
lifes = 5;
randomNumber = generateNumber();

} else {

cin >> gussedNumber;

if(cin)
{

if(gussedNumber == randomNumber)
{

// Correct Number
system("CLS");
cout << "ConGratz Bro, you hit the correct number!" << endl;
cout << "Lets try again. You now have 5 lifes left." << endl;
lifes = 5;
score = score + 1;

// Generate a new random number
randomNumber = generateNumber();

} else {

// Wrong Number
lifes = lifes - 1;
cout << "Wrong Number." << endl;
cout << "Number of lifes left: " << lifes << endl << endl;

}
} else {
cin.clear();
cin.ignore();
cout << "That was not a number!" << endl;
}
}
}
}

cout << randomNumber << endl;
return 0;
}

只是我边学习边做的一个简单的程序。

最佳答案

cin.ignore();

您只忽略了一个字符。您需要忽略整行:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

(您需要为 std::numeric_limits 包含 limits)。另请参阅 std::basic_istream::ignore ,它正好解决了您的问题。

关于多次打印 C++ 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15430776/

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