Reading an input file

I am trying to read an input file onto my screen and am having issues doing it. I am just trying to ask the user to tell me the file they want to open. Then open and see whats inside. I got a pro tip saying I am reading from the keyboard not the file but I am not sure how to change that.

Thanks for your help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 
//Reading a file 24 lines at a time

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main ()
{

	
	//filename = what the file is actually called on the computer
	string filename;
	string word;
	//PFname = what the program is calling the file
	fstream PFname;
	
	cout << "What file would you like to open? \n(Dont forget to add the extenstion e.g. ReadingAFile.cpp)";
	getline(cin,filename);
	

	PFname.open(filename.c_str() );
	
	//if must be name of what the program calls the file
	if (!PFname)
	{
		cout << "\nNo file of that name exists ";
	}
	else
	{
		cout << "In the else";
		
		getline(cin,word);
		
		while (!PFname.eof())
		{
			cout << word;
			getline(cin,word);
			
		}
		
		
	}

	PFname.close();
return 0;
}
Last edited on
line 36/41: replace cin with PFname. Better use it like so:
1
2
3
4
5
6
		cout << "In the else";
		
		while (getline(PFname,word)) // Note: getline return false in case of an error (like eof)
		{
			cout << word;
		}
coder777 thanks for your help! It was killing me I knew I was close thanks again!
Can somone help me out and explain what this while loop is doing. It is supposed to read in a file and it does that but it doesn't do the entire while loop seems like it only does line 6. In other words it doesn't use the variable count.

thanks in advance


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
while (getline(PFname,word))
		{
			int count = 2; 
			
			count ++;
			cout << word << "\n";
			
			cout << "\n\n" << count; //test line
			
			
			
			if (count >= 24)
			{
				cout << "Press any key to continue ";
				getch();
				count = 0;
			}
			
			
		}
The problem is on line 3: it is initializes count with 2 for each iteration and hence will never reach 24. Move that line above the loop.
Topic archived. No new replies allowed.