I am reading a CSV file and parsing its content into tokens. Now i want to know how to check for End of File. I am giving my code to be more clear.

ifstream file(filename);
if (file)
{
char ch ;
do
{ file.getline(line, SIZE);
tmp =static_cast<string>(line); 
vector <string> array; 
string token; 
istringstream iss(tmp);
int i=1;
while ( getline(iss, token, ',') )
{
array.push_back(token);

v_List.SetItemText(nItem, i, token.c_str());
i++;
}
// }//cin.get();
}while(ch=EOF); // Here i have to check for EOF but this one enters an infinite loop.

Help me !

try

ifstream file(filename);
if (file)
{
    while ( file.getline(line,SIZE) )
    {
        tmp =static_cast<string>(line);
        vector <string> array;
        string token;
        istringstream iss(tmp);
        int i=1;
        while ( getline(iss, token, ',') )
        {
            array.push_back(token);
            v_List.SetItemText(nItem, i, token.c_str());
            i++;
        }
    }
}
Member Avatar for iamthwee

Echo that and...

-don't use EOF or any of its derivatives.

here is a pure c++ version that replaces the C-style char array with std::string and removes the tmp variable altogether.

From the looks of this function it must be just a code snippet of a larger more complex function, is that right? If it isn't, then you can remove vector array because it serves no purpose.

ifstream file(filename);
if (file)
{
    std::string line;
    while ( getline(file,line) )
    {
       vector <string> array;
        istringstream iss(line);
        int i=1;
        while ( getline(iss, token, ',') )
        {
            array.push_back(token);
            v_List.SetItemText(nItem, i, token.c_str());
            i++;
        }
 }

You probably wouldn't need the temporary variable if you use something like this.

iifstream    file(filename);
string      line;
if (file)
{
    string token;
    stringstream iss;
    int i;
    while ( getline(file, line) )
    {
        iss << line;
        i = 1;
        while ( getline(iss, token, ',') )
        {
            cout << token << endl;
            i++;
        }
        iss.clear();
    }
}

edit:
Dragon has posted a more or less equal version before me. I considered deleting this but decided otherwise because of a subtle difference. That difference is that the stringstream variable is created before the while ( getline(file, line) ) block. I only wanted to refraining from calling the constructor over and over again. But the additional overhead (if any )due to the call of iss << line; and iss.clear(); should be inspected.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.