c++ - 从 CSV 数据文件中读取,尝试仅提取我需要的内容时出错
问题描述
我正在尝试从 CSV 文件中提取两列数据并转储其余数据。
我收到的错误是:
C2296: '>>': 非法,左操作数的类型为 'std::basic_istream> &(__thiscall std::basic_istream>::* )(_Elem *,std::streamsize)'
C3867: 'std::basic_istream>::read': 非标准语法;使用 '&' 创建指向成员的指针
数据格式如下:
1928,44.50%,.......
我希望将 1928 分配到 data.year 中,并将 44.50% 分配到 data.yield 中,但不包括百分号。
bool ReadData(MyData &data)
{
//Variable for reading data into file stream
ifstream inFile;
string trash;
char junk;
cout << "\nReading file . . .";
//Open data file
inFile.open("Data.csv");
//Read the first 18 lines, and throw it away
for (int i = 0; i < 18; ++i)
{
getline(inFile, trash);
}
//Read the necessary data into the arrays
for (int i = 0; i < SIZE; ++i)
{
//===============================================================
//This line is throwing 2 errors
//Goal: read first column of a simple integer into data.year, discard the comma, then read the second column of a double into data.yield, discard the percentage sign. infile.ignore(); to clear cin stream, getline(inFile, trash) to discard remainder of the lines.
inFile.read >> data.year[i] >> junk >> data.yield[i] >> junk >> trash >> endl;
//===============================================================
inFile.ignore();
getline(inFile, trash);
}
//Return false if file could not be opened
if (!inFile)
{
cout << "\n\nTechnical error! The file could not be read.";
return false;
}
else
{
cout << "\n\nFile opened successfully!";
return true;
}
inFile.close();
}
struct MyData
{
int year[SIZE];
int yield[SIZE];
double minYield;
double maxYield;
double avgYield;
};
我哪里错了?
解决方案
第一个问题是逐行读取文件的常量次数,但是您永远不知道文件的大小。因此,您应该在您的for loop
. 第二个问题是你说产量是一个int
但它double
在文件中是一个。第三个问题是读取格式化数据不像你做的那样。以下代码可以为您工作,或者您可以对代码进行一些操作。
for (int i = 0; i < SIZE && std::getline(infile, line); ++i) {
std::stringstream linestream(line);
std::string year, yield;
getline(linestream,year,',');
getline(linestream,yield,',');
yield.erase(std::remove(yield.begin(), yield.end(), '%'), yield.end()); // remove %
myData.year[i] = std::stoi( year ); // string to int
myData.yield[i] = std::stod( year ); // string to double
}
PS:不要忘记包含sstream
库。
推荐阅读
- css - CSS 粘性分组表头
- python - 为什么这个 else 语句不返回 False?
- google-cloud-platform - 有没有办法在向其发送流量之前测试完全托管的 Cloud Run 修订版?
- bash - 无法弄清楚如何实现这个bash参数
- vue.js - vuetify 数据表不显示数据
- reactjs - 反应:res.json() 数据未定义
- python - 抓取中途停止爬行
- android - 如何在 Android 登录中获取 Firebase 身份验证令牌
- sql - 在 Go 中推广 *sql.Rows 扫描
- flutter - 未处理的异常:MissingPluginException(在通道 com.tekartik.sqflite 上找不到方法 getDatabasesPath 的实现)