我在我的程序中使用cin和cout。我开始很好,因为它没有执行任何函数,但是在你输入你的名字后,它会在iostream库中引发异常。想知道通过参考使用cin是否有问题。
// 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->next != NULL) {
current = current->next;
count++;
}
return count;
}
void printlist() {
person *current = head;
while (current->next != NULL){
cout << "Name: " << current->name << " Age: " << current->age << "\n";
current = current->next;
}
}
void insert() {
// int choice;
person *newNode = (struct person*)malloc(sizeof(person));
//cout << "Press 1 to insert at beginning of list.\n";
//cin >> choice;
// switch (choice) {
//case 1:
newNode->next = head;
head = newNode;
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";
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();
}
使用visual studio 2015,是c / c ++的菜鸟,并尝试制作链表。
答案 0 :(得分:1)
问题是由您分配person
:
person *newNode = (struct person*)malloc(sizeof(person));
这将在堆上为person
的实例分配内存,但它不会调用person
及其任何成员的构造函数。这与age
和next
无关,因为它们是基本类型,但name
是std::string
,它有一个构造函数,需要调用才能使其正常运行
在C ++中,您可以使用关键字new
创建对象实例。
person *newNode = new person;
这将创建person的新实例,并调用其构造函数,该构造函数将正确初始化name
。
完成人员实例后,您将使用关键字delete
进行清理。
delete newNode;
类似于malloc
和new
之间的差异,delete
将free
内存,但也调用析构函数,name
使用析构函数清理它可能已分配用于存储字符串的任何资源。