【发布时间】:2015-08-30 16:07:31
【问题描述】:
我在我的程序中使用 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++ 的菜鸟,并试图制作一个链表。
【问题讨论】:
-
为什么在 C++ 中使用
malloc而不是new?这可能是您的问题之一,因为malloc只分配内存,它不构造对象(调用构造函数)。 -
person *newNode = (struct person*)malloc(sizeof(person));通过在对象的生命周期开始之前访问对象(person的构造函数从未运行),您的程序表现出未定义的行为。忘记 C++ 代码中的malloc,直接改成person *newNode = new person; -
没有像 c/c++ 这样的语言 - 你似乎同时使用了两者的元素,但这并没有真正起作用。
标签: c++