Read in a txt file and print it out

I have an assignment that prompts the user for a file name, and then print the contents of the file out to the screen. If the file doesn't exist it prompts the user until it gets a file that exists. I have this working for a specific file, test.txt, but i was wondering if i could get this to work for files in general. Also if anyone could assist with my while loop i would appreciate it, its an infinite loop and just keeps repeating file doesnt exist. Heres my code:

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
  1 #include <iostream>
  2 #include <fstream>
  3 #include <string>
  4 
  5 using namespace std;
  6 
  7 int main(){
  8 
  9         string filename;
 10         string temp;
 11 
 12         cout << "Please enter a filename." << endl;
 13 
 14         getline (cin,filename);
 15 
 16         ifstream infile(filename.c_str());
 17 
 18         getline (infile, temp);
 19 
 20         while(!infile){
 21                 cout << "Error, please re-enter filename." << endl;
 22                 getline(cin,filename);
 23                 ifstream infile(filename.c_str());
 24         }
 25 
 26         if(infile){
 27                 cout << temp << endl;}
 28 
 29 
 30 
 31         /*while(getline(infile, temp))
 32                 cout << temp << endl;
 33         infile.close();
 34 */
 35         cout << "Thanks." << endl;
 36 }
The loop is infinite because the infile you create on line 23 is different from the one of line 16. Just use open() instead of making a new ifstream.

And it looks like you are reading the file name fine. What problem was occurring when you tried to use a file other than test.txt?
The infinite loop occured, I was able to fix it because of your comment.

Thanks.
Topic archived. No new replies allowed.