0

I have to program a function which validates a number by reading a text file line by line. My problem is that this is a const stream. I thought that creating a new stream would help but my code is not compiling correctly.

bool validateNumber(const std::istream& n_is)
{
    while (!n_is.eof())
    {
        std::string line;
        std::istream test = n_is;
        std::getline(test,line); // read line

I get this error message:

/usr/include/c++/5/bits/ios_base.h:855:5: error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private.

What should I do to be able to read the stream even though it is const?

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
  • 3
    What is a "const stream"? Last time I checked, there's no such thing, and if there were, you wouldn't be able to read a single character out of it. Because it's `const`? – Sam Varshavchik Oct 05 '17 at 23:57
  • 3
    One cannot copy iostreams. `std::istream test = n_is;` tries to copy. Before the ability to `delete` functions showed up in c++11, the best solution was to make the function `private`. This is what you have run up against. The assignment operator is `private`. – user4581301 Oct 05 '17 at 23:57
  • 3
    by the way, `while (!n_is.eof())` is a bad idea. More here: [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301 Oct 05 '17 at 23:59

1 Answers1

3

std::istream is specifically designed to not allow copying, so your use of the test variable will not work.

Get rid of the test variable, drop the const from the n_is parameter, and use n_is directly with std:::getline():

bool validateNumber(std::istream& n_is)
{
    std::string line;
    while (std::getline(n_is, line)) // read line
    {
        ...
    }
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620