Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very basic C++ program issue - Invalid operands to binary expression

Tags:

c++

I just started teaching myself C++ on the Mac, and I have run into some issues.

I have written some code that allows the user to enter a number and when they hit enter, the number will be returned to the user.

Xcode will absolutely not have it though. Every time I try to run my code, it says that there is an issue with the cin>> thisisanumber; code.

The error comes up and says

Invalid operands to binary expression. Error is on line 10.

What am I doing wrong?

#include <iostream>

using namespace std;

int main()
{
   int thisisanumber();

   cout << "Please enter a number: ";
   cin  >> thisisanumber;
   cin.ignore();
   cout << "You entered"<< thisisanumber <<"\n";
   cin.get();
}
like image 715
Danny Avatar asked Jul 23 '12 21:07

Danny


4 Answers

You've fallen victim to the most vexing parse, which means thisisanumber is being treated as a function. Take out the parentheses and you should be fine:

int thisisanumber;

Also consider making it a bit more readable, such as thisIsANumber. If you ever need to know it, thisIsANumber uses the camel-case naming convention.

like image 110
chris Avatar answered Oct 16 '22 10:10

chris


Declare your variable without brackets, like

int thisisanumber;

With brackets, it is interpreted as a function, and a function can't be passed as a parameter to the >> operator.

like image 43
Péter Török Avatar answered Oct 16 '22 11:10

Péter Török


Your problem is the so called most vexing parse. Basically everything, which could be parsed as a function declaration will be parsed as such. Therefore the compiler will interpret int thisisanumber(); as a declaration of a function thisisanumber taking zero arguments and returning an int. If you consider this behaviour the problems with cin>>thisisanumber; should be somewhat selfevident.

If you remove the parantheses, changing the variable declaration to int thisisanumber;, your program should behave like you'd expect it to with thisisanumber being a variable of type int.

You might however reconsider your naming conventions, thisisanumber isn't exactly readable. I would suggest going with this_is_a_number, thisIsANumber or ThisIsANumber.

like image 2
Grizzly Avatar answered Oct 16 '22 12:10

Grizzly


int thisIsANumber;

try making it variable declaration because what you wrote has been interpreted as function.

like image 1
kiros hailay Avatar answered Oct 16 '22 10:10

kiros hailay