Question

i have some code that loops while going line by line through a text file to tokenise data and insert it into a vector.

i am using peek() to test if the file is at the end, and if so break the loop:

if (fin.peek() == -1)
    break;

this works fine, but i am a little bit annoyed about the inclusion of the "magic number" -1.. is there a library for C++ that i can include that functions the same as stdio.h that pre-defines -1 as EOF, or should i just define a const int eof = -1?

Était-ce utile?

La solution

The "magic value" -1 is defined as Traits::eof, where Traits is the traits_type typedef of the type of your fin variable.

In other word, decltype(fin)::traits_type::eof

Autres conseils

You want to use std::ios::eof(), something like:

if (fin.eof())

    break;

In general, loop controls should do the required input; if the input operation fails, the loop terminates:

std::string word;
while (std::cin >> word)
    std::cout << word << '\n';
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top