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?
This declaration
calls for a copy of
cinintoinputSuccessful. Copy constructor is deleted for streams, hence the error that you get. However, copying or taking a reference ofcinis pointless, because whatever you could do with a reference you could also do withcindirectly.You should make your variable
boolinstead:Now
inputSuccessfulwould containtrueif readingrepetitionswas successful, andfalseotherwise. The way this works is described in this Q&A.