首页 > 解决方案 > 从 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;
};

我哪里错了?

标签: c++visual-c++

解决方案


第一个问题是逐行读取文件的常量次数,但是您永远不知道文件的大小。因此,您应该在您的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库。


推荐阅读