我的輸入檔案userinfo.csv包含這種格式的用戶名和密碼username,password如下所示。
frierodablerbyo,Rey4gLmhM
pinkyandluluxo,7$J@XKu[
lifeincolorft,cmps9ufe
spirginti8z,95tcvbku
我想將所有用戶名和密碼存盤在
vector<string> usernames;
vector<string> passwords;
我從來沒有用過 C 來處理檔案,只用過 python
編輯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]);
}
}
我知道上面的代碼很糟糕,我該如何改進它,因為我的實際 csv 檔案包含 20000 行。
uj5u.com熱心網友回復:
已經發布的代碼片段很好,但請記住,CSV 分隔符是依賴于語言環境的,例如對于美國,它是一個 ',',對于德國,它將是 ';' 等等。此外,如果您的 CSV 中有可能包含這些字符之一的文本部分,則必須檢查左引號和右引號。
最簡單的方法是使用現成的庫來決議 CSV,例如https://github.com/d99kris/rapidcsv。
uj5u.com熱心網友回復:
你可以試試這樣的
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]));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365291.html
上一篇:透視csv并保留沒有熊貓的關鍵列
