Jump to content


Photo

File I/O in C++


  • Please log in to reply
5 replies to this topic

#1 jakevfr

jakevfr

    Young Padawan

  • Members
  • Pip
  • 40 posts

Posted 29 June 2006 - 12:30 PM

I'm trying to load numbers from a file. I've tried using getline() but that always says it cannot convert from char* to int. So I try the get() function and I get this
323 C:\My Documents\Jake's Documents\Dragons End\Helper.cpp no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::get(int&)'

What does it mean and what can I do.

And it's in a .txt file. Is that my problem?

#2 l3lueMage

l3lueMage

    Wanna Be Moderator

  • Publishing Betazoids
  • PipPipPipPip
  • 4,603 posts
  • Gender:Male
  • Location:Singapore

Posted 29 June 2006 - 01:57 PM

Can you show us the function that is reading the file?

#3 jakevfr

jakevfr

    Young Padawan

  • Members
  • Pip
  • 40 posts

Posted 29 June 2006 - 04:59 PM

void LoadGame() {
	 
	ifstream File("C:/stats.txt");
	
	char name[32];
	char load[32];
	int amount;
	
	File.getline(name,32);
	player.SetName(name);

		File.get(amount);
		player.SetAttack(amount);
	
		//Load Everything

	File.close();
	
	cout << player.GetName() << endl;

		cout << player.GetAttack() << endl;

		//Display Everything
	
	Wait();
}
Here it is.

Edited by jakevfr, 29 June 2006 - 05:01 PM.


#4 l3lueMage

l3lueMage

    Wanna Be Moderator

  • Publishing Betazoids
  • PipPipPipPip
  • 4,603 posts
  • Gender:Male
  • Location:Singapore

Posted 29 June 2006 - 05:49 PM

Its quite simple actually, if its a number all you need to do is

File >> amount

where amount is your integer you defined. and "File" is your ifstream variable, heres a sample function I made for you to look at, and if you want it to be an array then just add a for loop within to go through the different elements of the variable:
Input without For loop
int number;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
	while (! myfile.eof() )
	{
	  myfile >> number;
	}
	myfile.close();
  }

  else {
	  cout << "Unable to open file" << endl; 
  }

Example with for loop

int number[10];
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
	while (! myfile.eof() )
	{
		for(int x = 0; x < 10; x++) {
			myfile >> number[x];
		}
	}
	myfile.close();
  }

  else {
	  cout << "Unable to open file" << endl; 
  }


#5 jakevfr

jakevfr

    Young Padawan

  • Members
  • Pip
  • 40 posts

Posted 29 June 2006 - 06:16 PM

OK thanks :P

#6 l3lueMage

l3lueMage

    Wanna Be Moderator

  • Publishing Betazoids
  • PipPipPipPip
  • 4,603 posts
  • Gender:Male
  • Location:Singapore

Posted 29 June 2006 - 07:06 PM

No problem if you have any questions just ask :P




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users