Reading a file and displaying on the screen using getline: C ++

I am trying to read a file with the content below:

This is Line One This is Line Two This is Line Three This is Line Four This is Line Five 

code:

 #include <iostream> #include <fstream> #include <limits> using namespace std; int main() { char buff[50]; ifstream is("Test.txt"); if(!is) cout << "Unable to open Test.txt\n"; while(is.getline(buff,50,'\n')) { cout << is.gcount(); cout << buff; cout << "\n----------------\n"; } return 0; } 

Output:

 $ ./Trial 18This is Line One ---------------- 18This is Line Two ---------------- 20This is Line Three ---------------- 19This is Line Four ---------------- 17This is Line Five ---------------- 

Suppose now if I comment on cout << "\n----------------\n"; ie

  while(is.getline(buff,50,'\n')) { cout << is.gcount(); cout << buff; //cout << "\n----------------\n"; } 

I get output like:

 $ ./Trial 17This is Line Fivee 

I can’t understand - why such behavior?

Also why is it shown that the counter is 18 (suppose the first line - where the first line contains 16 characters, including spaces - if I add null, it becomes 17 - the end of line character is discarded by getline).

I am using windows-7 and cygwin.

+4
source share
3 answers

You declare:

I am using windows-7 and cygwin.

The problem is probably that the cygwin environment reads the file in binary mode, but the file is saved in DOS text format. This means that as each line exits, the ending character \r causes the next emitted line to overwrite the previous one.

Exit 18 compared to 16, as you expected, due to \r plus the final \n .

+3
source

It seems that each line is printed in the same place on the screen as the previous line. Since the last line of "17This is Line Five" is one character shorter than "20 This is Line Three" , the final 'e' in the last line remains, giving you "Fivee" .

Try printing a new line after each iteration of time, for example:

 while(is.getline(buff,50,'\n')) { cout << is.gcount(); cout << buff; cout << endl; // <- std::endl means "\n" } 
+1
source

The problem is that each line overwrites the previous line, which, in turn, is caused by the fact that the new line in the Windows / DOS text file is CR + LF ( "\r\n" ), but the gygwin version of the C library is not takes into account CR when reading a line. CR itself will move the cursor position back to the beginning of the line.

I have never used cygwin, but it’s nice to pretend that you are on a Unix style system when you are actually on Windows, which sometimes leads to such a problem. I don't know if there is an easy fix - running the file through dos2unix Test.txt should do the tho 'trick.

If I run this on my Linux machine, I get one long line of text, and not every line that overwrites each other.

(Optional "e" in five of the "three", which is longer than the "five")

0
source

Source: https://habr.com/ru/post/1480410/


All Articles