3

I am trying to enter some soccer player data into an array of soccerplayers (a structure)

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct sPlayer{
  char lname[20];
  char fname[20];
  int birthmonth;
  int birthday;
  int birthyear;
};

int main() {

  sPlayer players[10] = {};
  string input;
  string foo;

  ifstream inputFile;
  inputFile.open("players.txt");

  //check for error
  if (inputFile.fail()){
    cerr << "error opening file" << endl;
    exit(1);
  }

  int count = 0;
  while (!inputFile.eof()){

    getline(inputFile, input, ' ');
    players[count].lname = input;
    count++;

  }

  inputFile.close();

  cout << input;
  cout << "\n2–display original data, 3–sort data , 4–display sorted data 5–search by lastname 6–exit the program\n";
}

players.txt file:

Roberto Baggio 01 12 1992
David Beckham 05 12 1988
Pablo Aimar 05 13 1987
Michael Ballack 11 13 1999
Gabriel Batistuta 05 05 1979
Franz Beckenbauer 18 01 1976
Dennis Bergcamp 03 14 1989
Omar Bravo 03 03 1999
Jared Borgetti 09 23 1977
Fabio Cannavaro 02 25 1991

I get an error because I can't assign players[count].lname to input, but I don't know how to match up my data types. I am reading in 2 char arrays for fname and lname, 3 ints for birthday/month/year.

vince
  • 31
  • 2
  • You can't copy arrays. You can however copy `std::string` objects, which I really recommend you start using for all your strings. – Some programmer dude Jul 11 '19 at 09:53
  • 1
    Unrelated to your problem, but please read [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Some programmer dude Jul 11 '19 at 09:54

1 Answers1

3

There's a couple of things you could do, but which is correct might depend on other aspects of your project which you haven't told us about.

The simple thing would be do change your struct to use std::string instead of char arrays.

struct sPlayer{
  string lname;
  string fname;
  int birthmonth;
  int birthday;
  int birthyear;
};

Now your code will compile. This is undoubtedly the easy thing to do, so unless you have some good reason to use char arrays I would go with this.

The other thing you can do is perform the assignment from a std::string to a char array correctly. Arrays in C++ are poor and you have to take special steps if you want to copy them. In your code you could use the strcpy function

strcpy(players[count].lname, input.c_str());

This code is risky though because it will fail if the string you read doesn't fit into your 20 character array. You should check for that possibility before you do the copy.

And as already pointed out in the comments

while (!inputFile.eof()) {
    getline(inputFile, input, ' ');
    ...
}

is incorrect. The correct version is

while (getline(inputFile, input, ' ')) {
    ...
}
john
  • 71,156
  • 4
  • 49
  • 68