1 Replies - 325 Views - Last Post: 02 December 2009 - 04:52 AM Rate Topic: -----

#1 mono15591  Icon User is offline

  • D.I.C Regular

Reputation: 12
  • View blog
  • Posts: 406
  • Joined: 05-November 08

I/O again don't know why

Posted 02 December 2009 - 01:20 AM

Well the only thing I want to know is why this works
in_stream.open("data.txt");
			cout<< "data.txt: ";

			if(in_stream.is_open()==true){
				while(in_stream.eof()==false){
					getline(in_stream,file_data);
					
				}
				cout<< file_data;
				in_stream.close();
			}

and this doesn't
in_stream.open("data.txt");
			cout<< "data.txt: ";

			if(in_stream.is_open()==true){
				while(in_stream.eof()==false){
					getline(in_stream,file_data);
					cout<< file_data;
				}
				in_stream.close();
			}


The top one successfully displays whatever is in the file while the second one doesn't display it. My question is, why?
also I don't know why the indenting got messed up but I'm not going to fix it lol

Thanks in advance!

Is This A Good Question/Topic? 0
  • +

Replies To: I/O again don't know why

#2 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 282
  • View blog
  • Posts: 1,455
  • Joined: 16-May 09

Re: I/O again don't know why

Posted 02 December 2009 - 04:52 AM

I wrote this simple code and it works:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main (int argc, char * const argv[]) {
	string buf;
	ifstream in("data");
	if(in.is_open()) {
		while(!in.eof()) {
				getline(in, buf);
				cout<<buf<<endl;
		}
		in.close();
	}

	return 0;
}

Looking at your code, it seems exactly like mine... are you sure it doesn't work?
Edit: Your first code is not good as it only outputs the last line read from the file, and your second code should work just fine because mine works good :)

This post has been edited by Anarion: 02 December 2009 - 04:55 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1