C++流运算符的问题

C++ Issue with Stream Operators

本文关键字:问题 运算符 C++      更新时间:2023-10-16

我对 Cpp 很陌生,在声明输入流时遇到了一些问题。我不断收到一个错误,"错误:与'std::cin>> new_contact中的'运算符>>不匹配。Person::Name',以及一大堆其他事情,这些事情都与滥用它看起来像>>运算符有关。下面是代码,以及正在使用的每个结构的结构。

#include <iostream>
#include <map>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::endl;
using std::map;
using std::cout;
using std::cin;
typedef struct {
    string Name;
    map<string,int> Number;
} Person;
void addContact(vector<Person> Contacts) {
    Person new_contact;
    char ans;
    string name;
    cout << "What is the name of your new contact (first name)? " << endl;
    cin >> new_contact.Name;
    cout << "Do you want to enter a number for your contact? " << endl;
    cin >> ans;
    while (ans == 'y') {
        cout << "What type of number are you entering? " << endl; //ex CELL, FAX, HOME, WORK, etc.
        cin >> name;
        cout << "What is the number of your contact? " << endl;
        cin >> new_contact.Number[name];
        cout << "do you want to enter another number? " << endl;
        cin >> ans;
    }
    Contacts.push_back(new_contact);
}

请让我知道我哪里出了问题,因为在将我遇到的错误与人们遇到的以前的错误进行比较时,我没有看到任何明显的问题(大多数遇到此问题的人似乎将 endl 命令放在 cin 流的末尾,但是,我没有这样做(。提前感谢!

编辑:现在,我在尝试重新检查"answers"变量时陷入无限循环。该函数只是无限循环交替的"你想输入另一个数字吗?"和"你输入什么类型的数字?",而我没有输入。

cin >> new_contact.Name需要重载operator>>才能vector<char>,而 不存在。

最简单的解决方法是更改Name成员的类型:

string Name;