Question

I have some issue when I want to print out \n I'm using endl for that. And the problem is when I run the code on Windows7 it won't print out the newline. But it will print out newline in Ubuntu. Both OS is using the same compiler GNU g++.

So I wonder if there are some different way to print newline to file in Windows?

void translate(ofstream &out, const string &line, map<string, string> m)
{
   stringstream ss(line);
   string word;
   while(ss >> word)
   {
      if(m[word].size() == 0)
         out << "A";
      else
         out << m[word] << " ";
   }
   out << "\n";
}
Was it helpful?

Solution

Outputting either '\n' or using endl will result in the exact same content (the only difference is endl also flushes). When that \n character is written, if the file is in "text mode", the runtime library converts it to the platform's native mechanism to indicate lines. On unix, this is unnecessary because that mechanism is a \n byte. On Windows, that \n becomes \r\n (carriage return, line feed). I suspect you know all of this, but I'm reviewing it just in case.

In short, as long as your runtime library is setup for Windows, the code you have will work as you expect. I suspect you are using cygwin's g++, or some other g++ port, that is not setup for Windows-style lines, even in text mode. Some editors will not correctly interpret that untranslated \n.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top