2017-02-01 40 views
0

我試圖編寫一個程序,詢問用戶電影信息。將電影的信息作爲結構存儲在向量中,然後將結果輸出到具有返回類型爲void的2個函數的屏幕。我該如何解決這個指針/內存問題?

#include <iostream> 
#include <iomanip> 
#include <vector> 
#include <string> 
using namespace std; 

void make_movie(struct movie *film); 
void show_movie(vector <movie> data, int cnt); 

struct movie { 
    string name; 
    string director; 
    int year; 
    int duration; 
}; 

int main() { 

    int count = 0; 
    char input; 
    vector <movie> record; 
    movie *entry = nullptr; 

    do { 

     make_movie(entry); 
     record.push_back(*entry); 
     count++; 

     cout << endl; 
     cout << "Do you have more movie info to enter?\n"; 
     cout << "Enter y/Y for yes or n/N for no: "; 
     cin.ignore(); 
     cin >> input; 
     cout << endl; 


    } while (input == 'y' || input == 'Y'); 

    show_movie(record, record.size()); 

    return 0; 
} 

void make_movie(struct movie *film) { 

    cout << "Enter the title of the movie: "; 
    cin.ignore(); 
    getline(cin, film -> name); 

    cout << "Enter the director's name: "; 
    cin.ignore(); 
    getline(cin, film -> director); 

    cout << "Enter the year the movie was created: "; 
    cin >> film -> year; 

    cout << "Enter the movie length (in minutes): "; 
    cin >> film -> duration; 

} 

void show_movie(vector <movie> data, int cnt) { 

    cout << "Here is the info that you entered: " << endl; 

    for (int i = 0; i < cnt; i++) { 

     cout << "Movie Title: " << data[i].name << endl; 
     cout << "Movie Director: " << data[i].director << endl; 
     cout << "Movie Year: " << data[i].year << endl; 
     cout << "Movie Length: " << data[i].duration << endl; 
     cout << endl; 
    } 
} 

我得到一個錯誤,說我試圖訪問一個禁止的內存地址。

+0

'make_movie'應該由價值迴歸電影,不使用指針 –

回答

1

您需要更改量最少的是改變:

movie *entry = nullptr; 

do { 
    make_movie(entry); 
    record.push_back(*entry); 

到:

movie entry; 

do { 
    make_movie(&entry); 
    record.push_back(entry); 

進一步的改進將是:

  • 變化make_movie通過接受參數參考,那麼你的程序不使用任何指針,因此不容易受到任何問題屁股與指針相關聯。
  • 更改make_movie按值返回而不是參考參數。
  • cin.ignore();正在被錯誤地使用。你的程序將失去幾個輸入字符串的第一個字符。相反,刪除所有這些調用,並在make_movie函數結束時忽略當前行的其餘部分。此外,請將cin >> input;更改爲使用getline
0

你的錯誤
movie *entry = nullptr;


你有額外的cin.ignore();

cout << "Enter the title of the movie: "; 
// cin.ignore(); 
    getline(cin, film -> name); 

    cout << "Enter the director's name: "; 
// cin.ignore(); 
    getline(cin, film -> director); 

如何解決

movie main_info; 
movie* entry = &main_info; 

測試

intput:

Enter the title of the movie: any_thing 
Enter the director's name: yourself 
Enter the year the movie was created: 2016 
Enter the movie length (in minutes): 120 

Do you have more movie info to enter? 
Enter y/Y for yes or n/N for no: n 

輸出

Here is the info that you entered: 
Movie Title: any_thing 
Movie Director: yourself 
Movie Year: 2016 
Movie Length: 120 
相關問題