简体   繁体   English

如何从 C++ 中的 CSV 文件中正确读取数据

[英]How to properly read data from CSV file in C++

My input file userinfo.csv contains username and password in this format username,password shown below.我的输入文件userinfo.csv包含这种格式的用户名和密码用户名,密码如下所示。

frierodablerbyo,Rey4gLmhM
pinkyandluluxo,7$J@XKu[
lifeincolorft,cmps9ufe
spirginti8z,95tcvbku

I want to store all the usernames and passwords in我想将所有用户名和密码存储在

vector<string> usernames;
vector<string> passwords;

I've never used C++ for file handling, only python我从来没有使用 C++ 来处理文件,只有 python

EDIT1编辑1

#include <bits/stdc++.h>
using namespace std;

int main()
{
    fstream myfile;
    myfile.open("small.csv");

    vector<string> data;
    vector<string> usernames, passwords;

    while(myfile.good()){

        string word;
        getline(myfile, word, ',');
        data.push_back(word);
    }
    for(int i=0; i<8; i=i+2){
        usernames.push_back(data[i]);
    }
    for(int i=1; i<8; i=i+2){
        passwords.push_back(data[i]);
    }
}

I know above code is bad, how can I improve it because my actual csv file contains 20000 rows.我知道上面的代码很糟糕,我该如何改进它,因为我的实际 csv 文件包含 20000 行。

The code snipplet already posted is fine, but keep in mind that the CSV separators are locale-dependent, eg for US its a ',', for Germany it would be ';'已经发布的代码片段很好,但请记住,CSV 分隔符取决于区域设置,例如,对于美国,它是“,”,对于德国,它将是“;” and so on.等等。 Also if you have text sections in your CSV which might contain one of those characters, you have to check for opening and closing quotation marks.此外,如果 CSV 中的文本部分可能包含这些字符之一,则必须检查开始和结束引号。

The most easy thing to do is to use a ready-made library for parsing CSVs, for example https://github.com/d99kris/rapidcsv .最简单的做法是使用现成的库来解析 CSV,例如https://github.com/d99kris/rapidcsv

You can try something like this你可以试试这样的

std::vector <std::pair<std::string, std::string>> vec_credentials;

std::ifstream is("credentials.csv");
if(is.is_open())
{
    std::string line;
    while(getline(is, line))
    {
        std::stringstream ss(line);
        std::string token;
        std::vector <std::string> temp;
        // this is good if in the future you will have more than 2 columns
        while(getline(ss, token, ','))
        {
            temp.push_back(token);
        }
        vec_credentials.push_back(std::make_pair(temp[0], temp[1]));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM