在字符串库

时间:2015-08-17 23:39:58

标签: c++

我刚开始学习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();
}

1 个答案:

答案 0 :(得分:2)

您在包含C ++类成员的结构上使用malloc(在本例中为std :: string)。这是一个问题,因为C ++对象构造不会发生。通常,您希望使用message.root.node1.@attr1运算符而不是在C ++中调用malloc。

相关问题