Jump to content

Problems learning ifstream

- - - - -

  • Please log in to reply
2 replies to this topic

#1
JokiTate

JokiTate

    Newbie

  • Members
  • Pip
  • 3 posts
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.

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
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.
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

    Newbie

  • Members
  • Pip
  • 3 posts
LOL

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

Thanks.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users