[英]C++ endl with constants
I am just trying to familiarise myself with the basics of C++ moving from Java.我只是想让自己熟悉从 Java 迁移而来的 C++ 的基础知识。 I just wrote this functionality abstinent program and am coming across an error
test.cpp:15: error: expected primary-expression before '<<' token
and I am not sure why.我刚刚编写了这个功能禁欲程序,遇到了一个错误
test.cpp:15: error: expected primary-expression before '<<' token
我不知道为什么。
Anybody care to explain why endl
is not working with constants?有人愿意解释为什么
endl
不能使用常量吗? The code is below.代码如下。
//Includes to provide functionality.
#include <iostream>
//Uses the standard namespace.
using namespace std;
//Define constants.
#define STRING "C++ is working on this machine usig the GCC/G++ compiler";
//Main function.
int main()
{
string enteredString;
cout << STRING << endl;
cout << "Please enter a String:" << endl;
cin >> enteredString;
cout << "Your String was:" << endl;
cout << enteredString << endl;
return(0);
}
Your #define
has a semicolon at the end.您的
#define
末尾有一个分号。 That becomes part of the macro , so the pre-processed code looks like this:这成为宏的一部分,因此预处理代码如下所示:
cout << "C++ is working on this machine usig the GCC/G++ compiler"; << endl;
Remove the semicolon and you should be fine.删除分号,你应该没问题。
PS: It's usually a better idea to use real constants for this rather than relying on the preprocessor: PS:为此使用实常数而不是依赖预处理器通常是一个更好的主意:
const char *STRING = "C++ is working on this machine usig the GCC/G++ compiler";
You have a ;
你有一个
;
in your preprocessor definition.在您的预处理器定义中。 Note that
#DEFINE STRING x
just copies the whole x-statement (including the ;
) into the place where it's referenced.请注意,
#DEFINE STRING x
只是将整个 x 语句(包括;
)复制到引用它的位置。
Also, a preprocessor constant isn't a language constant.此外,预处理器常量不是语言常量。 You should use
const string STRING("C++ is working on this machine usig the GCC/G++ compiler");
你应该使用
const string STRING("C++ is working on this machine usig the GCC/G++ compiler");
You've got a secmi-colon at the end of your #define
- this will be substituted into your code, giving.您的
#define
末尾有一个分号 - 这将被替换到您的代码中,给出。
cout << "C++ is working on this machine usig the GCC/G++ compiler"; << endl;
Because you have a semi colon after STRING.因为您在 STRING 之后有一个分号。 Remove it and give it a try...
删除它并尝试一下...
Remove the ;
删除
;
in the STRINGS
definition在
STRINGS
定义中
Remove ;删除; from
从
#define STRING "C++ is working on this machine usig the GCC/G++ compiler"
Remove the ;
删除
;
at the end of #define STRING
and try again.在
#define STRING
末尾,然后重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.