Simple string output not as expected (new line appearing)

232 Views Asked by At

I have code equivalent to the following to print out a short string:

#include <iostream>
#include <string>

int main(int argc, const char* argv[])
{
  std::string s = "finished??/not finished??";
  std::cout << s << std::endl;
  return 0;
}

But the output is appearing across two lines and losing some characters:

finished  
ot finished??

But /n isn't the new line character! What's happening?

2

There are 2 best solutions below

0
On

In the first phase of translation (§2.2/1 of ISO/IEC 14882:2011(E)), sequences of characters known as trigraph sequences are replaced with single characters.

Trigraph sequences (2.4) are replaced by corresponding single-character internal representations.

One of the trigraphs maps ??/ to \. After the first phase, the code is equivalent to:

#include <iostream>
#include <string>

int main(int argc, const char* argv[])
{
  std::string s = "finished\not finished??";
  std::cout << s << std::endl;
  return 0;
}

As a result of the preprocessing phases, "finished\not finished??" is parsed as a string literal containing the escape-sequence \n which represents the new line character. The outputted string is therefore: finished<NL>ot finished??.

To avoid this, you need to escape one of the question marks as \?. This gives you:

#include <iostream>
#include <string>

int main(int argc, const char* argv[])
{
  std::string s = "finished?\?/not finished??";
  std::cout << s << std::endl;
  return 0;
}

This avoids the ??/ being picked up as a trigraph.

0
On

In gcc 4.1.2 I get this warning:

cd /devserv-home/rspikol/ g++ -g -o tz tz.C tz.C:6:28: warning: trigraph ??/ ignored, use -trigraphs to enable

Compilation finished at Wed Oct 3 12:43:16

So, by default, this version of gcc is not C++ standard compliant.

@sftrabbit: In my copy of the C++ standard, the paragraph is 2.3/1