将名称输入到动态数组的C ++循环在第一个字符串输入后显示奇怪的行为

我被分配一个类来创建一个地址簿,要求输入姓氏,首先,我决定将它们放在同一字符串中,并用空格分隔,输入后,程序开始显示一些意外的信息行为,并同时显示要求输入姓名和电话号码的提示。这是我的代码

#include <iostream>
#include <string>
using namespace std;

class AddressBook
{
private:
    struct Person
    {
        string name;
        int phone;
    };
    struct Person* arr;
    int count;

public:
    AddressBook(int size);
    void addName(string name,int phone);
    void sort();
    void Display();
    void findname(string name);
};

int main()
{
    AddressBook myAddressBook(20);
    std::string name;
    int phone;

    for (int i = 0; i < 5; i++)
    {
        cout << "Enter name,(Lastname Firstname): ";
        getline(std::cin,name);

        cout << "Enter phone number: ";
        cin >> phone;

        myAddressBook.addName(name,phone);
    }

    cout << "Enter a name to find it's phone number: ";
    getline(std::cin,name);
    myAddressBook.findname(name);

    cout << "Enter a name that is NOT in the addressbook: ";
    getline(std::cin,name);
    myAddressBook.findname(name);

    myAddressBook.Display();

    return 0;
}

AddressBook::AddressBook(int size)
{
    count = 0;
    arr = new Person[size];
}

void AddressBook::addName(string name,int phone)
{
    struct Person p;
    p.name = name;
    p.phone = phone;
    arr[count++] = p;
}

void AddressBook::sort()
{
    int n = count;

    for (int i = n - 1; i >= 0; i--)
    {
        for (int j = 0; j < i; j++)
        {
            if (arr[j].name > arr[j + 1].name)
            {
                struct Person temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void AddressBook::Display()
{
    sort();
    for (int i = 0; i < count; i++)
    {
        cout << arr[i].name << " : " << arr[i].phone << endl;
    }
}

void AddressBook::findname(string name)
{
    int i;
    for (i = 0; i < count; i++)
    {
        if (arr[i].name == name)
            break;
    }

    if (i == count)
    {
        cout << "Person not found! Try again please." << endl;
        return;
    }

    cout << "Phone Number : " << arr[i].phone << endl;
}
panxinli8 回答:将名称输入到动态数组的C ++循环在第一个字符串输入后显示奇怪的行为

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3038847.html

大家都在问