c++链表与字符串的问题

C++ Linked list issues with strings

本文关键字:问题 字符串 链表 c++      更新时间:2023-10-16

我对c++很陌生,目前正在尝试在用户可以设置的链表中插入电话号码和姓名。我想知道我在哪里出错了,我一直在看视频之后的视频,但一切都是关于在链表中使用整数,而不是字符串。

所以如果main被取出,程序显示(0)错误和(0)警告,所以我认为问题在main。

所以在main中,我试图cin nam(这是我在set_first的函数部分中所拥有的)。我试着给它一个地址,但我想我只是在捞救命稻草。

所以问题是:谁能给我指出正确的方向,或者告诉我如何将姓名和电话号码放入用户指定的节点中?

下面是main之后的所有程序:

#include <iostream>
#include <cstdlib>
#include "l_List_1.h"
using namespace std;
int main()
{
    l_List_1 obr;
    std::string nam;
    cout << "name";
    cin >> nam;
    obr.set_first(nam); //I'm trying to give it the nam since that's what I have inside my set_first function.

return 0;
}

我的头文件看起来像这样:

#ifndef L_LIST_1_H
#define L_LIST_1_H

class l_List_1
{
public:
    l_List_1();
    void set_first(std::string nam, int phnum);
    void delete_Node(std::string del_nams, int num_del);
    void display();
    char menu();

private:
    typedef struct node {
        std::string user_Name;
        int user_Phone;
        node* next;
    }* nodeptr;
    nodeptr head;
    nodeptr curr;
    nodeptr tail;
    nodeptr temp;
};
#endif // L_LIST_1_H

和我的CPP文件在这里:

#include <iostream>
#include <cstdlib>
#include <string>
#include "l_List_1.h"
using namespace std;

l_List_1::l_List_1()
{
    head = NULL;
    curr = NULL;
    tail = NULL;
}
void l_List_1::set_first(std::string nam, int phnum) {
    nodeptr n = new node;
    n->next = NULL;
    n->user_Name = nam;
    n->user_Phone = phnum;
    cout << "name";
    cin >> nam;
    if (head != NULL) {
        curr = head;
        while (curr->next != NULL) {
            curr = curr->next;
        }
        curr->next = n;
}
    else {
        head = n;
    }
}
void l_List_1::delete_Node(std::string del_nams, int num_del){
    nodeptr delptr = NULL;
    temp = head;
    curr = head;
    while(curr != NULL && curr->user_Name != del_nams && curr->user_Phone != num_del){
        temp = curr;
        curr = curr->next;
    }
    if(curr == NULL){
        cout << del_nams << "Was not in the list";
        cout << num_del << "was not in the list";
        delete delptr;
    } else{
        delptr = curr;
        curr = curr-> next;
        temp->next = curr;
        delete delptr;
        cout << "the item" << del_nams << "was deleted";
        cout << "the item" << num_del << "was deleted";
    }
}
void l_List_1::display(){
    curr = head;
    while(curr != NULL){
        cout << curr->user_Name;
        cout << curr->user_Phone << endl;
        curr = curr->next;
    }
}

对于初学者,成员函数set_first声明为两个参数

void set_first(std::string nam, int phnum);

但是你用一个参数调用

obr.set_first(nam); 

在函数本身(以及第二个删除节点的函数)中,不设置列表的尾部。

也不清楚这些语句在函数

中的作用
cout << "name";
cin >> nam;

你应该去掉它们。

并且没有必要声明以下数据成员

nodeptr curr;
nodeptr temp;

你可以在方法中使用局部变量来代替它们。

考虑你应该包括标题<string>

#include <string>

和我没有看到标题<cstdlib>的东西在你的程序中使用。