C++では、std::cin を利用してキーボードの入力を受け取ります。
#include <iostream>
int main()
{
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Hello " << name << "." << std::endl;
return 0;
}
Enter your name: Hanako
Hello Hanako.
では、cin と乱数を利用してじゃんけんゲームを作ってみます。
#include <iostream>
//#include <stdio.h> // 環境によって必要です
//#include <string> // 環境によって必要です
int you(std::string hand);
int computer();
void janken(int you, int computer);
int main()
{
srand(time(NULL));
std::string hand;
int opponent;
int yourself;
while (1)
{
std::cout << "グー:1 チョキ:2 パー:3 終了:4 ";
std::cin >> hand;
std::cout << "--------------------" << std::endl;
if (hand == "4")
{
std::cout << "Bye.." << std::endl;
break;
}
yourself = you(hand);
if (yourself)
{
opponent = computer();
janken(yourself, opponent);
}
}
return 0;
}
int you(std::string hand)
{
int num = atoi(hand.c_str());
switch (num)
{
case 1:
std::cout << "あなたはグーです。" << std::endl;
return num;
case 2:
std::cout << "あなたはチョキです。" << std::endl;
return num;
case 3:
std::cout << "あなたはパーです。" << std::endl;
return num;
default:
std::cout << "無効な値です。" << std::endl;
}
return 0;
}
int computer()
{
int num = rand() % 3 + 1;
switch (num)
{
case 1:
std::cout << "あいてはグーです。" << std::endl;
break;
case 2:
std::cout << "あいてはチョキです。" << std::endl;
break;
case 3:
std::cout << "あいてはパーです。" << std::endl;
break;
}
return num;
}
void janken(int you, int com)
{
if (you == com) {
std::cout << "あいこです。" << std::endl;
} else if (you == 1 && com == 2) {
std::cout << "あなたの勝ちです。" << std::endl;
} else if (you == 2 && com == 3) {
std::cout << "あなたの勝ちです。" << std::endl;
} else if (you == 3 && com == 1) {
std::cout << "あなたの勝ちです。" << std::endl;
} else {
std::cout << "あなたの負けです。" << std::endl;
}
}
グー:1 チョキ:2 パー:3 終了:4 0
--------------------
無効な値です。
グー:1 チョキ:2 パー:3 終了:4 1
--------------------
あなたはグーです。
あいてはチョキです。
あなたの勝ちです。
グー:1 チョキ:2 パー:3 終了:4 2
--------------------
あなたはチョキです。
あいてはチョキです。
あいこです。
グー:1 チョキ:2 パー:3 終了:4 3
--------------------
あなたはパーです。
あいてはグーです。
あなたの勝ちです。
グー:1 チョキ:2 パー:3 終了:4 4
--------------------
Bye..