我正在编写这个代码用于培训,我遇到了一个问题,如果我的用户写下他的名字后跟一个空格和其他东西,程序会弄乱我的流程。因此,如果你尝试这个小程序,当它要求提供名字时会更容易,就像“Robert Red”一样。问题发生在你在空间后面放了别的东西时,如果输入的只是“罗伯特”一切顺利的话。
这是代码:
// Description: This is a simple replica of the Japanese game Rock, Paper and
// Scissors.
// Author: Ernesto Campese
// Last Update: 11/04/2018
// Version: 0.0.1
#include "std_lib_facilities.h"
int main() {
string username = "";
char userinput;
int rounds = 0;
int wins = 0;
int draws = 0;
int loses = 0;
int user_secret = 0;
vector<string> options = {"Paper", "Scissors", "Rock"};
cout << "Enter your name: ";
cin >> username;
cout << "Welcome " << username << ", this is the game of Rock, Paper and Scissors.\n";
cout << username << " how many rounds you want to do? ";
cin >> rounds;
if (rounds <= 0) {
cout << "You need to play at least one round!\n";
rounds++;
}
cout << "The game is based on " << rounds << " rounds, you versus the CPU.\n";
cout << "Are you ready? (y/n): ";
cin >> userinput;
if (userinput != 'y') {
cout << "\nThank you.\nProgram Terminated by " << username;
return 0;
}
for(int i = 1; i <= rounds; i++) {
// Title of the rounds
if (i == 1) {
cout << "\nLet's start the first round!\n";
} else {
cout << "Round n. " << i << " begins!\n";
}
// USER makes a move
cout << "Which is your move? (r,p,s): ";
cin >> userinput;
cout << '\n' << username << " says... ";
switch (userinput) {
case 'r':
cout << "Rock\n";
user_secret = 2;
break;
case 'p':
cout << "Paper\n";
user_secret = 0;
break;
case 's':
cout << "Scissors\n";
user_secret = 1;
break;
default:
cout << "something weird...\n";
break;
}
// CPU makes a move
int cpu_secret = rand() % 3;
cout << "CPU says... " << options[cpu_secret] << "!\n";
// The program calculates the result.
if (user_secret == cpu_secret) {
draws++;
cout << username << " and the CPU draws!\n\n";
} else if (user_secret == 0 && cpu_secret == 2) {
wins++;
cout << username << " wins!\n\n";
} else if (user_secret == 1 && cpu_secret == 0) {
wins++;
cout << username << " wins!\n\n";
} else if (user_secret == 2 && cpu_secret == 1) {
wins++;
cout << username << " wins!\n\n";
} else {
loses++;
cout << username << " lose!\n\n";
}
}
cout << "\n\nBattle End!\n";
if (wins > loses) {
cout << username << " won the battle!\n";
} else if (loses > wins) {
cout << username << " lost the battle!\n";
} else {
cout << username << " draws the battle!\n";
}
cout << "Thank you " << username << "!\n";
}
您可以在此处尝试:Try me 谢谢!
答案 0 :(得分:3)
operator>>
在找到空白字符时停止读取输入。
使用std::getline()
读取带空格的用户输入。
使用您的代码的示例:
cout << "Enter your name: ";
getline(cin, username);
答案 1 :(得分:1)
如果您希望用户能够输入包含空格的名称,请使用std::getline()
代替operator>>
:
getline(cin, username);
否则,如果您希望用户只输入1个单词作为名称,并且您想忽略用户可能输入的任何其他内容,请使用std::cin.ignore()
:
#include <limits>
...
cin >> username;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
或者,您可以使用std::getline()
读取一行,然后使用std::istringstream
和operator>>
来提取该行的第一个字:
#include <sstream>
...
string line;
getline(cin, line);
istringstream(line) >> username;