开发者

C++ - error: expected primary-expression before '<<' token

When I 开发者_如何学Pythonadd this statment (the_pointer is of type int*)

<<"\nThe contents of the variable the_pointer is pointing at is : "<<*the_pointer;

The compiler returns the following error:

error: expected primary-expression before '<<' token

Why is that?

Thanks.


Judging by your comment to your question, you had something like this:

std::cout << x
          << y
          << z ;

This is all one statement, because there is no semi-colon statement terminator after x or y. But the next such line will fail, because of the semi-colon after z.


<< is an operator which takes two arguments - left-hand and right-hand. You have only provided the right-hand side. Change your code to:

std::cout << "\nThe contents of the variable the_pointer is pointing at is : " << *the_pointer;

And make sure you #include <iostream> near the top of your source file so you can use std::cout.


Because << is not a unary prefix operator, it needs two operands. When used for stream output, the left operand is an output stream, and the right operand is what you want to send to the stream. The result is a reference to the same stream, so you can append more << clauses to it. In any case, however, you need a left operand at all times.


The following program compiles and runs fine:

#include <iostream>

int main(int argc, char *argv[]) {
    int val = 10;
    int *ptr_val = &val;
    std::cout << "pointer value: \n";
    std::cout << *ptr_val;
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜