Miles
Miles

Reputation: 2537

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 errortest.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);
}

Upvotes: 0

Views: 463

Answers (8)

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

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.

Upvotes: 0

yasouser
yasouser

Reputation: 5177

Remove the ; at the end of #define STRING and try again.

Upvotes: 1

Bruno Alano
Bruno Alano

Reputation: 643

Remove ; from

#define STRING "C++ is working on this machine usig the GCC/G++ compiler"

Upvotes: 1

KillianDS
KillianDS

Reputation: 17186

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

Upvotes: 6

Node
Node

Reputation: 3509

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;

Upvotes: 2

littleadv
littleadv

Reputation: 20272

Remove the ; in the STRINGS definition

Upvotes: 1

Leandro T. C. Melo
Leandro T. C. Melo

Reputation: 4032

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

Upvotes: 1

hammar
hammar

Reputation: 139890

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

Upvotes: 8

Related Questions