试图进入字符串时的分割故障

segmentation fault when trying to cin into a string?

本文关键字:分割 故障 字符串      更新时间:2023-10-16

hi需要此分割故障的帮助,不知道为什么我得到它

Movie *newMovie = (Movie*) malloc(sizeof(Movie));
cout << "nEnter the next movie title:   ";
cin >> newMovie->title;
class Movie {
  public:
    Movie();
    std::string title;
    int year;
    GenreType genre;
};

我检查了DGB并在CIN线上有任何建议吗?btw标题是电影类型的实例,是std :: string

除非您真的知道需要它,否则不要在C 中使用malloc(提示:不)。

malloc分配内存,但它不调用任何构造函数 - 它只会为您所看到的一个字节提供大量字节。假装这些字节中有一个对象,当没有构造时,这些字节不起作用。

这样做:

Movie *newMovie = new Movie();
cout << "nEnter the next movie title:   ";
cin >> newMovie->title;

您首先需要动态分配吗?为什么不只是:

Movie newMovie;
cout << "nEnter the next movie title:   ";
cin >> newMovie.title;

简单的AMD安全方法不使用动态分配:

Movie newMovie;
cout << "nEnter the next movie title:   ";
cin >> newMovie.title;
Movie newMovie;
cout << "nEnter the next movie title ";
cin >> newMovie.title;

将做技巧