954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to Read an input file

I am having difficulty reading the following input file

Jon 40
Chris 50
Pete 60

what is wrong with this code that I wrote to read the above file. thank you for your help.

//*****************
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
#include <iomanip>
#include<cassert>
using namespace std;


void main()
{
	char InputFileName[] ="in.txt";
	char OutputFileName[]="out.txt";
	ifstream InFile;
	ofstream OutFile;
	InFile.open(InputFileName);

	if(!InFile)
	{
		cout<<"Not Open"<<endl;
		exit(1);
	}

	OutFile.open(OutputFileName);

	if(!OutFile)
	{
		cout<<" Can not Open output file"<<endl;
		exit(1);
	}

	char c;
	string name;
	int age;

	while(!InFile)
	{

		 InFile>>name>>age;
	
		OutFile<<name<<"  "<<age<<endl;
		if(InFile.eof()) break;
	}
	InFile.close();
	OutFile.close();

}


<< moderator edit: added [code][/code] tags >>

mkcee
Newbie Poster
1 post since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

You're thinking too hard. :)

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>

int main()
{
  const char InputFileName[] ="in.txt";
  const char OutputFileName[]="out.txt";

  std::ifstream InFile(InputFileName);
  std::ofstream OutFile(OutputFileName);

  if (!InFile || !OutFile) {
    std::cerr << "File open failure\n";
    std::exit(EXIT_FAILURE);
  }

  std::string name;
  int age;

  while (InFile >> name >> age)
    Outfile << name << ' ' << age << '\n';
}
Dogtree
Posting Whiz in Training
233 posts since May 2005
Reputation Points: 35
Solved Threads: 3
 

what is the different functions on file input output c++

nutristars
Newbie Poster
1 post since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You