If you define the variable as
const int quantity;
you're saying "I'd like an int
called quantity
, and under no circumstances do I want its value to ever change." As a result, if you then write
cin >> quantity;
the compiler says something to the effect of "wait - you want me to change the value of quantity
by replacing it with whatever the user entered, but earlier you said that you never wanted me to change it!"
My sense is that you wanted to make it so that after you give an initial value to quantity
that value never changes, but with const
variables that initial value needs to be set when the variable is created. You could therefore try something like this:
const int quantity = readValue();
for some function readValue()
that reads and returns an int
value. That way, the compiler sees that quantity
is given a fixed value, it knows that the value never changes, and you never try to directly cin
into the value of quantity
.
For a more technical perspective on the errors you got: when the compiler read
const int quantity;
without any value assigned to it, it reported an error because it's unusual to create a constant without giving it a value. (I can see from your code that you meant to give it a value, but the way you did it wasn't legal and the compiler didn't piece the two things together). The second error about operator >>
resulted because none of the different ways that you can read something from cin
(read a string, read an int
, read a char
, etc.) applied, since each of them assumed that they can get a mutable (modifiable) view of the value in question. Again, both of these issues stem from the fact that the compiler saw your code as two separate independent errors rather than one large "oops, that's not how const
works" error.