简体   繁体   中英

C++ endl with constants

I am just trying to familiarise myself with the basics of C++ moving from Java. 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.

Anybody care to explain why endl is not working with constants? 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. 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:

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.

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");

You've got a secmi-colon at the end of your #define - this will be substituted into your code, giving.

cout << "C++ is working on this machine usig the GCC/G++ compiler"; << endl;

Because you have a semi colon after STRING. Remove it and give it a try...

Remove the ; in the STRINGS definition

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 is a preprocessor directive. This replaces everything that follows the defined macro, in this case STRING. So, remove the last semicolon (;) that puts an end-of-statement marker while being expanded in the offending line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM