Digital Cat
Digital Cat

Reputation: 3

I am stuck with this struct in C++

I am currently learning "struct" in C++ and stuck at this:

#include "iostream"
#define SIZE 100

struct date{
  int day;
  int month;
  int year;
};

typedef struct{
  char *name;
  struct date date_of_birth;
  int score;
} person;

void entry(person *roster){
  person temp;
  std::cout << "Input name: " << '\n';
  gets(temp.name);
  std::cout << "Date of birth: " << '\n';
  std::cin >> temp.date_of_birth.day;
  std::cin >> temp.date_of_birth.month;
  std::cin >> temp.date_of_birth.year;
  std::cout << "Score: " << '\n';
  std::cin >> temp.score;
  *roster = temp;
}

int main(int argc, char const *argv[]) {
  person roster[SIZE];
  // number of people in roster:
  int n;
  std::cin >> n;
  for (int i = 0; i < n; i++){
    entry(&roster[i]);
  }
  return 0;
}

The program ended just right after I input the n value. Plz help me with this problem, thank you so much

Upvotes: 0

Views: 109

Answers (1)

G. Sliepen
G. Sliepen

Reputation: 7973

The problem is that gets(temp.name) does not allocate memory for the string for you, it expects temp.name to already point to allocated storage. However, temp.name was never initialized, at best your program will crash trying to read the name, at worst it will seem to work but will overwrite memory that will cause problems later. Even if you provide it with a buffer, gets() doesn't know how big your buffer is and will happily write past the end of the buffer it the line it tries to read is long enough. This is why gets() is a deprecated function that has been removed since C11, and my compiler won't even compile your code.

To read in a line, either use the POSIX function getline(), which is not standard C or C++, or use C++'s std::getline() function. However, the latter requires you to read into a std::string, not into a char *.

Finally, as Thomas Matthews mentioned in the comments, don't mix C++'s I/O functions with C I/O functions, so std::getline() is the way to go.

Upvotes: 1

Related Questions