How to properly read data from CSV file in C++

Advertisements

My input file userinfo.csv contains username and password in this format username,password shown below.

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

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

I know above code is bad, how can I improve it because my actual csv file contains 20000 rows.

>Solution :

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

Leave a ReplyCancel reply