Search code examples
c++cinistream

Error when assigning the return of (cin >> someVar) to an istream variable in C++


I just started learning C++ as an additional language and came across the problem mentioned in the title. Here's the code I started out with:

#include "HelloWorldWriter.h"
#include <iostream>

using namespace std;

int HelloWorldWriter::getNumberOfRepetitions() {
    cout << "Enter number of Hello Worlds: ";
    int repetitions = 0;
    if(cin >> repetitions){
        if(repetitions > 0){
            return repetitions;
        }
    } else{
        return 0;
    }
}

...

I assumed that cin >> repetitions would store the user input value into repetitions and return true if the user has entered something that could be parsed into an integer, and false otherwise. I then tried to assign the result of cin >> repetitions to a boolean, but it produced an error, saying "Types bool and istream are not compatible". I then tried the following assignment:

istream inputSuccessful = cin >> repetitions;

This however produced an error, saying "basic_istream::basic_istream(const basic_istream &) is deleted".

I have the following questions now:

1) When using cin >> someInt (with integer someInt as a target/argument), what behaviour (value in target variable, return value, behaviour during the next call of that operator,...) should you expect, if the user enters a word with no leading numbers (i.e. that can't be parsed into an integer)?

2) How would you save the result of cin >> someInt in a variable? What type would it have to be? How does that value relate to boolean expressions?


Solution

  • This declaration

    istream inputSuccessful = cin >> repetitions;
    

    calls for a copy of cin into inputSuccessful. Copy constructor is deleted for streams, hence the error that you get. However, copying or taking a reference of cin is pointless, because whatever you could do with a reference you could also do with cin directly.

    You should make your variable bool instead:

    bool inputSuccessful(cin >> repetitions);
    

    Now inputSuccessful would contain true if reading repetitions was successful, and false otherwise. The way this works is described in this Q&A.