我正在尝试编写一个非常基本的程序来读取CSV并显示它。如下所示,该功能是一个非常基本的功能。在显示每个单元格之前,它使用getline读取每一行(直到换行符)。它工作正常,当getline完全停止工作时,我正在调整循环以显示每个单元格。在不更改任何与getline相关的代码的情况下,我编译了它并且它不会从文件中读取。行总是空的。但是,ifstream是有效的,因为“test”字符串(我在响应中插入)从sheet fine中读入。任何人都可以帮助我吗?
PS:之前我遇到过与getline类似的问题。这与我的系统有关吗?它似乎可以开启和关闭
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream sheet( "StockTake.csv", ios::app );
if ( ! sheet.is_open() )
{
cout << "Cannot Open File!\n";
return 0;
}
else
{
cout << "Opened File\n";
}
//Now print each row (find the newline chracter at the end of each line)
/*string test;
sheet >> test;
cout << test;*/
for ( string row; ! sheet.eof(); getline(sheet, row, '\n') )
{
if (row == "")
{
cout << "Bad Read. Exiting\n";
return 0;
}
//Print out each row with a tab space between each cell
string cell;
//find the beginning and the end of each cell
for (int i = 0, j = 0; ; )
{
/*Checks if the cell is enclosed in quotes
The first time, j == i hence the -2 and +2
the +2 is required to "skip" out the apostrophes if
they are found*/
if (row.at(i) == '"')
{
i++;
j = i-2;
do
{
j = row.find('"', j+2);
} while (row.at(j+1) == '"');
/*Check for the "" apostrophe sign*/
}
else
{
j = row.find(',', i);
}
/*Print the Cell*/
if (j == string::npos) //if this is the last cell
{
cell = row.substr(i, row.size() - i);
}
else if ( j-i != 0)
{
cell = row.substr(i, j-i);
}
else
{
cell = "";
}
/*Check for the "" apostrophe sign, and replace
with " for each instance*/
if ( cell.find("\"\"", 0) != string::npos )
{
int pos = -2; //must start at zero
do
{
//Skips out the "current" apostrophe
//if there are more than one
pos = cell.find("\"\"", pos+2);
cell = cell.substr(0, pos) +
cell.substr(pos+1, cell.size()- (pos+1) );
} while (cell.find("\"\"", pos+2) != string::npos);
}
/*Display the Cell, only the space will be displayed
if the cell is empty*/
cout << cell << " ";
/*Find the next cell*/
if ( row.at(j) == '"' )
{
i = j+2;
}
else
{
i = j+1;
}
}
cout << "\n"; //Print newline character at the end of each line
}
return 0;
}