-3

I know that every line of an input file contains five numbers, and I want my c++ program to automatically determine how many lines are in the file without asking the user. Is there a way to do this without using getline or the string class?

Fred Toews
  • 51
  • 1
  • 7
  • 6
    This question's http://stackoverflow.com/questions/3482064/counting-the-number-of-lines-in-a-text-file top-voted answer presents 2 methodologies that do not use std::string or getline. One solution is a C-style file reading using `getc()` and one is a C++ `istream_iterator` solution. – sunny Oct 29 '15 at 18:28
  • Why can't you use `getline` or `std::string`? – Thomas Matthews Oct 29 '15 at 19:41

2 Answers2

0

This is how I would do it...

#include <iostream> 
#include <fstream>

using namespace std;

int main()
{
    string fileName = "Data.txt";
    std::ifstream f(fileName, std::ifstream::ate | std::ifstream::binary);
    int fileSize = f.tellg() / 5 * sizeof(int);

    return 0;
}

The code assumes a file named Data.txt and that the 5 numbers on each line are of type int and are not separated by space or delimiters. Keep in mind that in the case of a text file, each line will terminate to a newline so this technique, which does not take them into account, will give misleading results.

dspfnder
  • 1,049
  • 1
  • 8
  • 12
0

Sure, all you have to do is simply read the file, while checking for the escape sequences. Note, that the \n escape sequence is translated to system-specific newline escape sequence when writing and vice versa while reading in text mode.

In general, this code snippet might help you.

Given the file somefile.txt

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Compiling the code below and inputing the file name somefile.txt

#include <iostream>
#include <fstream>

inline size_t newlineCount (std::istream& stream)
{
    size_t linesCount = 0;
    while (true)
    {
        int extracted = stream.get();
        if (stream.eof()) return linesCount;
        else if (extracted == '\n') ++linesCount;
    }
}

int main(int argc, char* argv[])
{
    std::string filename;
    std::cout << "File: ";
    std::cin >> filename;
    std::ifstream fileStream;
    fileStream.exceptions(fileStream.goodbit);
    fileStream.open(filename.c_str(), std::ifstream::in);
    if (!fileStream.good())
    {
        std::cerr << "Error opening file \"" << filename << "\". Aborting." << std::endl;
        exit(-1);
    }
    std::cout << "Lines in file: " << newlineCount(fileStream) << std::endl;
    fileStream.close();
}

Gives the output

File: somefile.txt
Lines in file: 4