Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Problems learning ifstream

stream

  • Please log in to reply
2 replies to this topic

#1 JokiTate

JokiTate

    CC Lurker

  • New Member
  • Pip
  • 3 posts

Posted 10 February 2012 - 05:45 PM

I don't understand what is wrong with my code here...

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <time.h>

using namespace std;

int create_file(char Filename[128]) {
	cout << "Creating file " << Filename << endl;
	srand(time(NULL));
	ifstream theFile;
	theFile.open(Filename);
	for (int x=0; x < 24; x++) {
		double number = (rand() % 10000 + 1);
		theFile << "Entry" << x << " " << number;
		if (theFile.fail() {
			cout << "create_file failed!";
			return 1;
		}
	}
	theFile.close();
	return 0;
}

void read_file(char Filename[128]) {
	cout << "Reading file" << Filename << endl;
	ifstream theFile;
	theFile.open(Filename);
	bool z=1;
	while (z) {
		string theString;
		theFile >> theString;
		cout << theString;
		if (theFile.fail()) {
			z = 0;
		}
	}
}

int main () {
	char Filename[128] = "thefile.txt";
	if (create_file(Filename)) {
		cout << "create_file returned 1";
	}
	read_file(Filename);
}

/home/john/examples/src/files.cxx:16: error: no match for ‘operator<<’ in ‘theFile << "Entry"’

Specifically line 16.
  • 0

#2 gregwarner

gregwarner

    Obi Wan of Programming

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1586 posts
  • Location:Arkansas
  • Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 10 February 2012 - 07:59 PM

The ifstream class has not had the << operator defined in it. The << operator is an insertion operator, meant to be used with output streams, not input streams. In your code above, you're trying to write data out to an input stream, which doesn't make sense.
  • 0

ti-99-sig.png
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#3 JokiTate

JokiTate

    CC Lurker

  • New Member
  • Pip
  • 3 posts

Posted 10 February 2012 - 08:37 PM

LOL

Now I see there are specific classes to create file input and output objects.

Thanks.
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download