从 CSV 文件中Unordered_map值

Unordered_map values from CSV file

本文关键字:map Unordered CSV 文件      更新时间:2023-10-16

我找到了一个我正在尝试实现的类似示例:

std::unordered_map<std::string,std::string> mymap = {
  {"us","United States"},
  {"uk","United Kingdom"},
  {"fr","France"},
  {"de","Germany"}
};

但是,我拥有的值在 CSV 文件中。

我是否需要将这些值插入到不同的容器中,然后将它们添加到unordered_map中,或者是否可以直接从文件添加它们?

正在努力弄清楚,所以目前我只是将文件内容写到屏幕上:

int menuLoop = 1;
int userChoice;
string getInput;
while(menuLoop == 1)
{
    cout << "Menunn" 
         << "1. 20n"
         << "2. 100n"
         << "3. 500n"
         << "4. 1000n"
         << "5. 10,000n"
         << "6. 50,000nn";
    cin >> userChoice;
    if(userChoice == 1)
    {
        cout << "n20nn";
        string getContent;
        ifstream openFile("20.txt");
        if(openFile.is_open())
        {
            while(!openFile.eof())
            {
                getline(openFile, getContent);
                cout << getContent << endl;
            }
        }
        system("PAUSE"); 
    }
}

文件的内容:

Bpgvjdfj,Bvfbyfzc
Zjmvxouu,Fsmotsaa
Xocbwmnd,Fcdlnmhb
Fsmotsaa,Zexyegma
Bvfbyfzc,Qkignteu
Uysmwjdb,Wzujllbk
Fwhbryyz,Byoifnrp
Klqljfrk,Bpgvjdfj
Qkignteu,Wgqtalnh
Wgqtalnh,Coyuhnbx
Sgtgyldw,Fwhbryyz
Coyuhnbx,Zjmvxouu
Zvjxfwkx,Sgtgyldw
Czeagvnj,Uysmwjdb
Oljgjisa,Dffkuztu
Zexyegma,Zvjxfwkx
Fcdlnmhb,Klqljfrk
Wzujllbk,Oljgjisa
Byoifnrp,Czeagvnj

要提取数据,请使用 CSV 解析器库或使用逗号作为分隔符手动拆分文件的每一行。CSV 文件与文本文件没有什么不同;它们只是遵循独特的数据格式。

中间数据结构是不必要的。假设您的数据采用 [key],[value] 格式,请使用此处unordered_map的C++文档正确插入数据。

例:

string line;
getline(file, line);
// simple split (alternatively, use strtok)
string key = line.substr(0,line.find(','));
string value = line.substr(line.find(',')+1);
unordered_map<string,string> mymap;
mymap[key] = value;

编辑:us2012 带有分隔符的 getline 方法也特别有用。还要记住,在读取带有分隔符的 CSV 作为数据时必须注意,通常由用引号括起来的值表示:

"hello, world","hola","mundo"

有关 CSV 格式的更多信息,请参阅此处。

可以直接在 getline 中指定分隔符。

        while(true)
        {
            string key, value;
            //try to read key, if there is none, break
            if (!getline(openFile, key, ',')) break;
            //read value
            getline(openFile, value, 'n');
            mymap[key] = value;
            cout << key << ":" << value << endl;
        }

请注意,当前循环检查您是否在文件末尾太晚,并且将生成空键,值对。这在上面得到了纠正。