假设我有:
Charlie Smith 134
Alice Jones 245
Bob Richards Hughes 325
在数据文件中,我想将它们读入 map ,我该怎么做?
此代码仅适用于名字,不确定如何将其扩展到许多名字...
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <iterator>
#define TRUE 1
#define FALSE 0
int main() {
std::map<std::string, int> contents;
std::map<std::string, int>::iterator it;
bool repeat(true);
std::ifstream infile;
while (repeat) {
repeat = false;
std::cout << "Enter the filename: " << std::endl;
std::string filename;
std::getline (std::cin, filename);
infile.open(filename.c_str());
if (infile.fail()) {
std::cerr << "Invalid Filename" << std::endl;
repeat = true;
}
}
while(!infile.eof()) {
int a;
std::string b;
infile >> b >> a;
contents[b]=a;
}
std::cout << "\n";
for (it = contents.begin(); it != contents.end(); it++) {
std::cout << it->first << " " << it->second << std::endl;
}
return 0;
}
最佳答案
一次读取整行(参见 std::getline
),然后向后搜索最后空格(例如 std::string::find_last_of
)。这是将名称与编号分开的空格。然后使用 std::string::substr
将名称放入其自己的字符串中,并使用例如解析数字std::stoi
.
注意:带有全名的字符串末尾会有一个或多个空格,您需要在使用该字符串作为键之前删除它们。
关于c++ - 如何将带有 ID 号的名称列表读入 map C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22990284/