gpt4 book ai didi

c++ - 在C++中以分隔符读取文件

转载 作者:行者123 更新时间:2023-12-01 15:12:54 24 4
gpt4 key购买 nike

我有一个将文本文件读入 vector 的脚本。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;

struct Items
{
string Name;
int Number1;
double Number2;
};

int main()
{
ifstream file("file4.txt");
vector<Items> player_data;
Items player_info;
while (file >> player_info.Name >> player_info.Number1 >> player_info.Number2) {
player_data.push_back(player_info);
}

for (auto &i : player_data) {
std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
}
}
file4.txt包含以下内容:
Wogger Wabbit
2
6.2
Bilbo Baggins
111
81.3
Mary Poppins
29
154.8

如何正确显示数据?我怎样才能给分隔符一个换行符( '\n')?

最佳答案

您的代码有一些问题;此解决方案有效,但并不优雅。我敢肯定,这里的人可以给你或引导你去一个更优雅的人:)

首先-打开文件后,您需要检查文件是否打开

其次-最好使用 std::getline() 从文件中读取,因为它可以获取整行。 >>在进入空间时停止。

另外,尽量不要使用 using namespace std

编辑

如果文件无法打开,则添加错误的打印

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cerrno>
#include <cstring>

using namespace std;

struct Items
{
string Name;
int Number1;
double Number2;
};

int main()
{
ifstream file("text4.text");
if(!file.is_open()) // <- check if file opened correctly
{
std::cout << std::strerror(errno); // <- print the reason why the file didnt open
return 0;
}
vector<Items> player_data;
Items player_info;
std::string line;
while(std::getline(file,line)) // <-- read lines and stop when the file is finished
{
player_info.Name = line;
std::getline(file,line);
player_info.Number1 = stoi(line);
std::getline(file,line);
player_info.Number2 = stod(line);
player_data.push_back(player_info);
}


for (auto &i : player_data) {
std::cout << i.Name << ", " << i.Number1 << ", " << i.Number2 << endl;
}
}

关于c++ - 在C++中以分隔符读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62146584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com