0

Aim: to read a string in the form First\nSecond from a file and to print it as

 First
 Second

Problem: if the string is defined in the code, as in line = "First\nSecond";, then it is printed on two lines; if instead I read it from a file then is printed as

First\nSecond

Short program illustrating the problem:

#include "stdafx.h"     // I'm using Visual Studio 2008
#include <fstream>
#include <string>
#include <iostream>

void main() {
  std::ifstream ParameterFile( "parameters.par" ) ;
  std::string line ;
  getline (ParameterFile, line) ;
  std::cout << line << std::endl ;
  line = "First\nSecond";
  std::cout << line << std::endl ;

  return;
}

The parameters.par file contains only the line

First\nSecond

The Win32 console output is

C:\blabla>SOtest.exe
First\nSecond
First
Second

Any suggestion?

  • I have now written an answer to explain that, though coproc's is already pretty good. Did you read it? – Lightness Races in Orbit Jan 23 '15 at 17:04
  • The compiler replaces \n (when inside string literals) with the newline character. The function getline does not perform such a replacement; you have to do the replacement yourself (see my answer below) – coproc Jan 23 '15 at 17:10

2 Answers2

2

In C/C++ string literals ("...") the backslash is used to mark so called "escape sequences" for special characters. The compiler translates (replaces) the two characters '\' (ASCII code 92) followed by 'n' (ASCII code 110) by the new-line character (ASCII code 10). In a text file one would normally just hit the [RETURN] key to insert a newline character. If you really need to process input containing the two characters '\' and 'n' and want to handle them like a C/C++ compiler then you must explicitely replace them by the newline character:

replace(line, "\\n", "\n");

where you have to supply a replace function like this: Replace part of a string with another string (Standard C++ does not supply such a replace function by itself.)

Other escape sequences supported by C/C++ and similar compilers:

  • \t -> [TAB]
  • \" -> " (to distinguish from a plain ", which marks the end of a string literal, but is not part of the string itself!)
  • \\ -> \ (to allow having a backslash in a string literal; a single backslash starts an escape sequence)
Community
  • 1
  • 1
coproc
  • 6,027
  • 2
  • 20
  • 31
2

The character indicated in a string literal by the escape sequence \n is not the same as the sequence of characters that looks like \n!

When you think you're assigning First\nSecond, you're not. In your source code, \n in a string literal is a "shortcut" for the invisible newline character. The string does not contain \n - it contains the newline character. It's automatically converted for you.

Whereas what you're reading from your file is the actual characters \ and n.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055