[英]C++ Read Tab Delimited File Into Vector and Display It
Im trying to read a tab delimited file into a string vector and display it. 我试图将制表符分隔的文件读入字符串向量并显示它。 But I am not getting the desired output.
但是我没有得到想要的输出。
This is the file I am trying to read in and display: 这是我尝试读取并显示的文件:
1 amazon billybob@kfc.com password!23
2 facebook digitalGlut3n@ello.mail fri3dMayoNaize
3 bank.com brokeDude@sofa.com LostTheRemot3!.Crap
This is my display function: 这是我的显示功能:
void DisplayRecords() {
vector<string> vRecords;
ifstream inFile("database.txt");
string entry;
while (inFile >> entry) {
vRecords.push_back(entry);
}
for (int i = 0; i < vRecords.size(); i++) {
if (i % 4 == 0) {
cout << "\n";
}
cout << setw(5) << vRecords[i];
}
cout << "\n\n";
}
And this is the output I get: 这是我得到的输出:
1amazonbillybob@kfc.compassword!23
2facebookdigitalGlut3n@ello.mailfri3dMayoNaize
3bank.combrokeDude@sofa.comLostTheRemot3!.CrapPress any key to continue . . .
How would I get my function to display similar to the original file with spaces between strings? 如何使函数显示与原始文件相似的字符串之间有空格?
A vector of individual strings really does not make a lot of sense for structured data. 单个字符串的向量对于结构化数据确实没有多大意义。 A vector of structs would make more sense, eg:
结构向量更有意义,例如:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
struct Record
{
std::string id;
std::string site;
std::string user;
std::string pass;
};
void DisplayRecords()
{
std::vector<Record> vRecords;
std::ifstream inFile("database.txt");
std::string entry;
while (std::getline(inFile, entry))
{
std::istringstream iss(entry);
Record rec;
std::getline(iss, rec.id, '\t');
std::getline(iss, rec.site, '\t');
std::getline(iss, rec.user, '\t');
std::getline(iss, rec.pass, '\t');
vRecords.push_back(rec);
}
for (int i = 0; i < vRecords.size(); ++i)
{
Record &rec = vRecords[i];
std::cout << std::setw(5) << rec.id
<< std::setw(10) << rec.site
<< std::setw(30) << rec.user
<< std::setw(30) << rec.pass
<< "\n";
}
std::cout << "\n";
}
if your database file is fixed format. 如果您的数据库文件是固定格式。
you can get answer through below code. 您可以通过以下代码获得答案。
void DisplayRecords() {
vector<string> vRecords;
ifstream inFile("database.txt");
string entry;
while (inFile >> entry) {
vRecords.push_back(entry);
vRecords.emplace_back("\t");
}
for (int i = 0; i < vRecords.size(); i++) {
if (i % 8 == 0) {
cout << "\n";
}
cout << setw(5) << vRecords[i];
}
cout << "\n\n";
}
in this code, entry variable is 1, amazon, .... in while loop. 在此代码中,while循环中的入口变量为1,亚马逊,...。
so, i added tab between each strings. 因此,我在每个字符串之间添加了制表符。
and print new line, when i%8 == 0 is true. 并在i%8 == 0为true时打印新行。
i wish it was helpful to you. 我希望它对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.