Frederic Chang
Frederic Chang

Reputation: 549

Getline doesn't work when I use count function

I cannot find the information about that why I cannot print the details from Test.txt when I run count function first?

But when I tried to switch count function with While loop, it works, but the program cannot print the line counts anymore.

Problem

void ReadDataFromFileLBLIntoCharArray()
{
    ifstream fin("Test.txt");
    const int LINE_LENGTH = 100;
    char str[LINE_LENGTH];
    cout << count(std::istreambuf_iterator<char>(fin),std::istreambuf_iterator<char>(), '\n') << endl;
    cout << "GG" << endl;
    while( fin.getline(str,LINE_LENGTH) )
    {
        cout << "Read from file: " << str << endl;
    }
}

No Problem

void ReadDataFromFileLBLIntoCharArray()
{
    ifstream fin("Test.txt");
    const int LINE_LENGTH = 100;
    char str[LINE_LENGTH];

    cout << "GG" << endl;
    while( fin.getline(str,LINE_LENGTH) )
    {
        cout << "Read from file: " << str << endl;
    }
    cout << count(std::istreambuf_iterator<char>(fin),std::istreambuf_iterator<char>(), '\n') << endl;
}

Upvotes: 0

Views: 89

Answers (1)

R Sahu
R Sahu

Reputation: 206717

In both cases, you are attempting to read the contents of the file twice, In order to do that, you need:

  1. Clear the error states of the ifstream.
  2. Rewind the ifstream.
void ReadDataFromFileLBLIntoCharArray()
{
    ifstream fin("Test.txt");
    const int LINE_LENGTH = 100;
    char str[LINE_LENGTH];
    cout << count(std::istreambuf_iterator<char>(fin),std::istreambuf_iterator<char>(), '\n') << endl;
    cout << "GG" << endl;

    // Add these lines
    fin.clear();
    fin.seekg(0); // rewind

    while( fin.getline(str,LINE_LENGTH) )
    {
        cout << "Read from file: " << str << endl;
    }
}


void ReadDataFromFileLBLIntoCharArray()
{
    ifstream fin("Test.txt");
    const int LINE_LENGTH = 100;
    char str[LINE_LENGTH];

    cout << "GG" << endl;
    while( fin.getline(str,LINE_LENGTH) )
    {
        cout << "Read from file: " << str << endl;
    }

    // Add these lines
    fin.clear();
    fin.seekg(0); // rewind


    cout << count(std::istreambuf_iterator<char>(fin),std::istreambuf_iterator<char>(), '\n') << endl;
}

Upvotes: 1

Related Questions