【发布时间】: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