Hello there,
I wanna add the Computer as a Player, if there are only 3 player who play the game.
My first try was this:
int numberofplayers;
cout << "How much players? : ";
cin >> numberofplayers;
string computer = "Computer";
string* players = new string[numberofplayers];
if (numberofplayers== 3)
{
for (int i = 0; i < numberofplayers; i++)
{
cout << "players " << i + 1 << ", tell me your name: ";
cin >> players [i];
}
players [4] = computer;
cout << "Player 4 is the computer! " << endl;
}
my goal is now to see all players :
for (int i = 1; i <= numberofplayers; i++)
{
cout << players[i] << "\t";
}
My problem is now that i can not see the 4th player which ist the Computer.
Can someone can tell me how i can see the Computer as a player?
I think you are off by one.
an array is indexed from zero, which you seem to know: your for loop is correct. But you mess with players[4] which is the FIFTH PLAYER. Player 4 is [3] because 0,1,2,3 is 4 things... right?
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
int numberofplayers;
cout << "How many players? : ";
cin >> numberofplayers;
vector<string> players(numberofplayers);
for (size_t i = 0; i < players.size(); i++)
{
cout << "Player " << i + 1 << ", tell me your name: ";
cin >> players[i];
}
if (numberofplayers == 3)
{
const string computer = "Computer";
cout << "Player 4 is the computer!\n";
players.push_back(computer);
}
for (size_t i = 0; i < players.size(); i++)
{
cout << players[i] << "\t";
}
cout << '\n';
}
How many players? : 3
Player 1, tell me your name: Alice
Player 2, tell me your name: Bob
Player 3, tell me your name: Charlie
Player 4 is the computer!
Alice Bob Charlie Computer