i need assistence finishing the C++ problem

here is the problem

Write a program named FileIO.cpp. In your program, open the input file in.txt, check to see if it opens successfully, and then read the names from the input file and print to screen the names of all the Presidents’ numbered, so number 1 before displaying the first name, print the number 2 before displaying the second name, and so on for each name in the file. This process continues until all the names from the input file are read.

Your output on to the screen should look like:

1. George Washington

2. John Adams

3. Thomas Jefferson

4. James Madison

5. James Monroe

6. John Quincy Adams

I don't know how to add a number in front of the presidents name
heres what I have so far:

#include <fstream>
using namespace std;
int main () {
int i;
ofstream fout;
ifstream gout;
fout.open ("presidents.txt");
fout<< "George Washington"<<endl;
fout<< "John Adams"<<endl;
fout<< "Thomas Jefferson"<<endl;
fout<< "James Monroe"<<endl;
fout<< "John Quincy Adams"<<endl;
fout.close();

gout.open("presidents.txt");
if(gout.fail())
{
cout<<"file open fail!";
}

else {
string president_name;
while (getline(gout,president_name))
cout<<president_name <<endl;
}
gout.close ();

}
Last edited on
It sounds like you're given the file in.txt as part of the assignment. Do you have that? Can you paste it here?
Create a text file (this will be your input file) named in.txt in your current working directory. Your input file should have Presidents’ names (one on each line). You can have as many as you wish:

For example:

George Washington

John Adams

Thomas Jefferson

James Madison

James Monroe

John Quincy Adams
I think the part you're missing is that your program should not create the input file. You should create that using notepad or something similar.

So the part of your program that creates the file isn't necessary:
1
2
3
4
5
6
7
8
9
ofstream fout;
ifstream gout;
fout.open ("presidents.txt");
fout<< "George Washington"<<endl;
fout<< "John Adams"<<endl;
fout<< "Thomas Jefferson"<<endl;
fout<< "James Monroe"<<endl;
fout<< "John Quincy Adams"<<endl;
fout.close();


Make that change and then get your code working so that it reads the names and prints them out. Once that is working, figure out what to add so that it prints the number before each president's name.
Topic archived. No new replies allowed.