c++ - 如何将带有 ID 号的名称列表读入 map C++

标签 c++ string fstream

假设我有:

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/

相关文章:

c++ - 更改 QWebView 中的突出显示颜色

c++ - 关于单元测试(googletest)和项目/文件夹/文件的混淆

java - 从Java中的输入获取字符串

javascript - 测试输入值是否匹配常量值

c - For 循环不以空终止符终止

c++ - 从文件中读取时遇到问题。似乎过早地达到了 EOF

c++ - 多个重载函数实例与参数列表匹配

c++ - Eclipse 中 C++ 调试的 macOS 10.15 Catalina gdb 问题

c++ - 为什么 ofstream 不触发 IN_CREATE

c++ - 多次访问 r/w 中的文件