Wei-Cheng Liu
Wei-Cheng Liu

Reputation: 113

error: expected primary-expression before 'int'

I am a beginner of C++. I am reading a book about C++. I use g++ to compile the following program, which is an example in the book:

/*modified fig1-1.cpp*/
#include <iostream>
using namespace std;
int main()
{
    cout << "\n Enter an integer";
    cin >> (int i);
    cout << "\n Enter a character";
    cin >> (char c);
    return 0;
}

Then I get the following error messages:

fig1-2.cpp: In function 'int main()':
fig1-2.cpp:7:10: error: expected primary-expression before 'int'
  cin >> (int i);
          ^
fig1-2.cpp:7:10: error: expected ')' before 'int'
fig1-2.cpp:9:10: error: expected primary-expression before 'char'
  cin >> (char c);
          ^
fig1-2.cpp:9:10: error: expected ')' before 'char'

Could anyone please tell me what happend? Thank you very much in advance.

Upvotes: 1

Views: 9727

Answers (2)

Sandeep Singh
Sandeep Singh

Reputation: 21

you can not use as you are doing you will have to declare i or c first as i have done so

int main()
{
int i;
char c;
cout << "\n Enter an integer";
cin >> (i);
cout << "\n Enter a character";
cin >> (c);
return 0;   
}

Upvotes: 0

user4407569
user4407569

Reputation:

int i is the syntax for a declaration. It may not appear inside an expression, which should follow cin >>.

First declare your variable and then use it:

int i;
cin >> i;

The same for char c:

chat c;
cin >> c;

And I heavily doubt that this is an example in a book teaching C++. It is blatantly wrong syntax. If it really is in the book as a supposedly working example (i.e. not to explain the error), then you should get a different book.

Upvotes: 2

Related Questions