名字和姓氏不一起读入集合

First and last names not reading in together into set

我在读取一个全是名字的文本文件(有些是重复的)并将名字和姓氏一起输入一行时遇到问题。该程序可以运行并删除重复的名称,但按字母顺序输出它们,名字和姓氏被视为 2 个不同的名称。我是否输出错误的名称:

string name;
while (partyList >> name)
{
    NamesList.insert(name);
}

cout << "Here is the party list without repetion: " << endl;
while (!NamesList.empty())                                                  {
    cout << ' ' << *NamesList.begin() << endl;
    NamesList.erase(NamesList.begin());
}

?

文本文件是 PartyList.txt,它包含:

Daniel Walrus
Amy Giester
Jim Carry
Gregg Lunch
Irony Max
Jim Carry
Daniel Walrus          
Gregg Lunch

目前我的输出是:

Amy 
Carrey
Daniel
Giester
Gregg
Irony
Jim
Lunch
Max
Walrus

这是我的代码(这是一个更大的任务的一部分,除了将名字和姓氏放在一起之外还完成了):

#include <iostream>
#include <fstream>
#include <string>
#include <set>

using namespace std;
void PartyList();

int main()
{
PartyList();
system("PAUSE");
return 0;
}

void PartyList()
{
fstream partyList;
partyList.open("PartyList.txt", fstream::in);

if (!partyList)
{
    cout << "Couldn't open file!" << endl;
}

set<string> NamesList;
string name;
while (partyList >> name)
{
    NamesList.insert(name);
}

cout << "Here is the party list without repetion: " << endl;                    
while(!NamesList.empty())                                                   {                                                                               cout << ' ' << *NamesList.begin() << endl;                                  
    NamesList.erase(NamesList.begin());
}
//cout << name << endl;

cout << endl;
}
while (partyList >> name)

>> 运算符正在此处查找第一个空白字符。这就是为什么你的名字是这样分开的。

partyList >> name 中的 >> 运算符只从 partyList 读取直到空格,其中包括空格,因此 name 得到值 "Daniel""Walrus""Amy" 等迭代。如果你想一次读一行,使用

while (std::getline(partyList, name))

这让你 "Daniel Walrus" 等等