开发者

I want to give a string a value of one

开发者 https://www.devze.com 2022-12-12 11:18 出处:网络
I\'m entering team names into a soccer league. I have an array set up so that the league can take at most 4 teams,

I'm entering team names into a soccer league.

I have an array set up so that the league can take at most 4 teams,

I also have an array that states that the number of teams in the league is exactly 4 teams.

So I want to set up a counter which stops me from entering too 开发者_JS百科many team names.

This is a small chunk of my code

str teamName

for(int i = 0; i < leagueSize; i++)

cout << "Enter a Team Name"<<endl'
cin >> teamName; 

so is there a way for me to give a team name a value of 1 so that each time I enter a team name it decrements the number in the array until I can't add any more teams?

I am new at c++ and haven't been learning for that long so I might be totally off here.

Thanks in advance.


You're almost there, you are just missing some curly braces, and you need to declare an array instead of a single string for the team names:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
 int leagueSize = 4;
 string teamNames[leagueSize];
 for (int i = 0; i < leagueSize; i++) {
  cout << "Enter a team name:" << endl;
  cin >> teamNames[i];
 }

 cout << endl;
 cout << "The following teams have been entered:" << endl;
 for (int i = 0; i < leagueSize; i++) {
  cout << "Team " << (i + 1) << ": " << teamNames[i] << endl;
 }
}


A for controls structure (as well as if, else and while), executes the next single statement or block. So in your example:

for(int i = 0; i < leagueSize; i++)
    cout << "Enter a Team Name"<<endl;
cin >> teamName;

Only the output statement is part of the for loop and the input statement happens only once after the entire loop is finished.

So, what you want to do is put your code in a block:

for(int i = 0; i < leagueSize; i++)
{
    cout << "Enter a Team Name"<<endl;
    cin >> teamName;
}

Many C and C++ coding styles recommend you always use a block even if you only have a single statement:

for (...)
{
    one-statement;
}


Ok, so I've edited the code a bit,

The exact instructions say: write a function to enter all the team names and set all the other variables

So its ok for me to do all that in one function isn't it?

This is the full function that I've come up with void addTeam(T *T, char *teamName, int i) {
str teamName[leagueSize];

for(int i = 0; i < leagueSize; i++)

{
cout << "Enter a Team Name"<<endl'
cin >> teamName[i]; 
}

cout << endl;
cout << "The following teams have been entered:" << endl;
for (int i = 0; i < leagueSize; i++) {
cout << "Team " << (i + 1) << ": " << teamNames[i] << endl;


T[i].name = teamName;
T[i].numPoints = 0;
T[i].numGoalsFor = 0;
T[i].numGoalsAgainst = 0;
T[i].numMatchesPlayed = 0;
T[i].numMatchesWon = 0;
T[i].numMatchesLost = 0;
T[i].numMatchesDrawn = 0;  

}

0

精彩评论

暂无评论...
验证码 换一张
取 消