gpt4 book ai didi

c++ - 获取字符串库中抛出的异常

转载 作者:行者123 更新时间:2023-11-28 02:22:03 25 4
gpt4 key购买 nike

<分区>

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com