2015-08-17 58 views
0

我剛開始學習C++,並且製作了一個簡單的鏈接列表程序。問題在於,它正在從字符串庫和打印列表中獲取拋出的異常。當我調用malloc時,我將其縮小爲一個錯誤,但我不知道如何修復它,或者其他異常。獲取字符串庫中拋出的異常

// linkedlists.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include <iostream> 
#include <string> 
using namespace std; 
struct person { 
    string name; 
    int age; 
    struct person* next; 
}; 
person *head = NULL; 
int length() { 
    int count = 0; 
    person *current = head; 
    while (current->age != NULL) { 
     current = current->next; 
     count++; 
    } 
    return count; 
} 
void printlist() { 
    person * current = head; 
    while (current->next != NULL){ //exception is here. 
     cout << "Name: " << current->name << " Age: " << current->age <<   "\n"; 
     current = current->next; 
    } 
} 
void insert() { 
// int choice; 
    person *newNode = (struct person*) malloc(sizeof(person));//assuming exception is here because it is showing an exception at the size function in string library, and the struct person has string name. 
    //cout << "Press 1 to insert at beginning of list.\n"; 
    //cin >> choice; 
// switch (choice) { 
    //case 1: 

    *newNode->next = *head; 
    cout << "What is this person's name?\n"; 
    cin >> newNode->name; 
    cout << "\nWhat is the age of " << newNode->name << "?"; 
    cin >> newNode->age; 
    cout << "The current list of people is " << length() << " long.\n"; 
    printlist(); 

} 
void menu() { 
    int choice; 
    cout << "Welcome to the person recorder! "; 
    bool inloop = true; 
    while (inloop) { 
     cout << "Press 1 to add more entries. Press 2 to print the entire list. Press 3 to exit the program.\n"; //error in string when i press 1. error in the while loop when i press 2. 
     cin >> choice; 
     switch (choice) { 
     case 1: 
      insert(); 
     case 2: 
      printlist(); 
     case 3: 
      inloop = false; 
     } 
    } 
} 
/*void change(person* human) { 
    string temp_name; 
    int temp_age; 
    cout << "What is this person's name?\n"; 
    cin >> temp_name; 
    cout << "\nWhat is this person's age?\n"; 
    cin >> temp_age; 
    human->name = temp_name; 
    human->age = temp_age; 
} 
*/ 
int main() 
{ 
    menu(); 
} 
+5

這是功課嗎?如果是這樣,你的教授應該停止教授「C++」 –

+0

你應該能夠使用一個調試器準確地追蹤出現程序崩潰的異常。你也沒有真正包括你得到的錯誤。 「例外」可能意味着更多的事情。它們可能是指定爲無效參數引發的異常(例如,接收不是數字的字符串的「std :: stoi」)。它們可以通過實現放置在那裏,標準不太友善(例如,使用GCC從空指針創建'std :: string')。他們甚至可能不是C++異常(例如Windows中的SEH)。全部都有錯誤信息。 – chris

回答

2

您在包含C++類成員(本例中爲std :: string)的結構上使用malloc。這是一個問題,因爲C++對象構造不會發生。一般來說,你想使用new運算符而不是在C++中調用malloc。

+0

我的意思是,如果必須的話,你不會希望使用'new',而是一個智能指針。但'new'肯定比'malloc'好。 – chris

+0

@chris我同意,這是在C++環境中另一個榮耀C的例子。 –

相關問題