gpt4 book ai didi

具有多个值的 C++ 文件解析器

转载 作者:行者123 更新时间:2023-11-27 23:02:43 27 4
gpt4 key购买 nike

我正在尝试编写 C++ 代码来打开一个 csv 文件并从一行中读取多个输入。所以csv文件的数据类型格式为:

int, string, int, int

我想做的是像这样一次将所有这些读入一个变量

ifstream myfile;
myfile.open("input.csv");
string a;
int b, c, d;
while (myfile.is_open() && myfile.good())
{
if(myfile >> b >> a >> c >> d)
cout << a << " " << b << " " << c << " " << d << " " ;
myfile.close();
}

但是当我运行我的代码时,它只是跳过 if 行并转到 .close() 行。什么都没有打印出来。我认为它无法读取这些值。

我的代码有什么问题?为什么它不能读取这些值?

最佳答案

执行以下操作以从正确 格式化的 csv 文件中提取 token 。

#include <sstream>
// ....

std::string line ;

while ( std::getline( myfile, line ) )
{

std::stringstream buffer( line );
std::string token;

while( std::getline( buffer, token, ',' ) )
{
// std::cout << token << std::endl;
// convert to int, etc
}
}

关于具有多个值的 C++ 文件解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210504/

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