【问题标题】:How to properly read data from CSV file in C++如何在 C++ 中正确地从 CSV 文件中读取数据
【发布时间】:2022-01-01 18:00:45
【问题描述】:

我的输入文件 userinfo.csv 包含如下格式的用户名和密码 username,password

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

我想将所有的用户名和密码存储在

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

我从来没有使用过 C++ 来处理文件,只有 python

EDIT1

#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]);
    }
}

我知道上面的代码很糟糕,我该如何改进它,因为我的实际 csv 文件包含 20000 行。

【问题讨论】:

  • 打开文件(查找std::ifstream),逐行读取(std::getline),然后用逗号分割字符串。
  • 你好,这个网站上的人喜欢看到 OP 在提问之前付出了一些努力。你能告诉我到目前为止你尝试了什么吗?网上有很多这样的例子。
  • 建议:不要拆分属于一起的数据,最好存储起来。 G。在std::map 中,成对的向量或具有名称和密码成员的自定义结构的向量。两个单独的向量很容易出错,因为您必须在两个向量中并行进行任何修改总是(-> 在某些时候重复代码)。
  • 你应该关注including bits/stdc++.h
  • 读取csv参考this

标签: c++ string csv file-pointer


【解决方案1】:

已经发布的代码片段很好,但请记住,CSV 分隔符取决于区域设置,例如。 G。对于美国,它是',',对于德国,它会是';'等等。此外,如果 CSV 中的文本部分可能包含这些字符之一,则必须检查开始和结束引号。

最简单的做法是使用现成的库来解析 CSV,例如https://github.com/d99kris/rapidcsv

【讨论】:

  • 使用库来处理非常简单的 csvs 是相当过分的。
  • 谢谢,这个库看起来很酷,我一定会在我未来的项目中使用它。
【解决方案2】:

你可以试试这样的

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]));
    }
    is.close();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2015-02-05
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多