fstream Reading Carriage Return

How do I read a carriage return in a text file and cout?

while ( inFile >> data ) { // read file .
if( data == "\n") // how can i recognize "new lines"
cout << "\n";
}
Read it as a character (ie, into a char).
1
2
3
4
5
6
7
8
	char ch;
	while((ch = file.get()) != EOF)
	{
		if(ch == '\n')
		{
			cout<<"New Line"<<endl;
		}
	}
is there a similar way using strings?
You can abuse getline() to do it:
1
2
3
  string all_text_in_file;
  ifstream myfile( 'fooey' );
  getline( myfile, all_text_in_file, '\0' );  // this assumes the null char is not in the file 


Otherwise you will have to stick to using get() or read().

If that doesn't help, then please explain what you mean by "using strings".
I want to read file and cout the way it looks within the file

Hello World! 11 001
34 040 33
22


what it is doing is cout like "Hello World! 11 001 34 040 33 22"


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ifstream inFile;
string file data;
inFile.open("test.txt", ios::in);
    

cout << "File contents = " ;
		
while ( !inFile.eof() ) {
	inFile >> data ;
	cout << data;
	cout << " ";

            if ( data == "\n"  )  // this has to be the error... maybe data needs to be converted to char... not sure
                  cout << "\n";
}


also I want keep the functionality to check "data" and compare it to keywords
Ah...

What is happening is a common affliction. You are misunderstanding how STL streams work.

The >> operator is for parsing input data into numbers, etc. It always delineates on whitespace (which is space, tab, vertical tab, linefeed, carriage return). Basically it is a friendly replacement for what C people use scanf().

If you want to track where the line ends, you can peek() for '\n':
1
2
3
4
5
6
7
8
string datum;
while (inFile >> datum) {
  cout << datum;
  if (inFile.peek() == '\n')
    cout << '\n';
  else
    cout << ' ';
  }

or you can just read everything one line at a time:
1
2
3
string data;
while (getline( inFile, data ))
  cout << data << '\n';


Notice that in the first, you read each datum (whitespace-separated string) one at a time. In the second, you read an entire line (which may contain zero or more whitespace-separated strings) at a time.

Hope this helps.
Thank you very much that was a big help!

:D
Topic archived. No new replies allowed.