Thread: Getting user input for filename loop

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    12

    Question Getting user input for filename loop

    I have a program that prompts the user for an existing text file that they want my program to modify. Currently, when the user puts in a file that can't be found, the program displays an error message then quits. I would prefer to put the prompt in a while loop and while the file can't be found, prompt the user to try to input the file name again. I set up my loop but it doesn't work. THis is how I tried it:

    Code:
    cin>>input_file;
    
    	fin.open(input_file);
    
    	while (fin.fail())
    	{
    		fin.close();
    		cout<<"Error opening input file. Did you input the wrong name or path?\n";
    		cout<<"\nEnter the name of the text file: \n\n";
    		cin>>input_file;
    
    	fin.open(input_file);
    	}
    At first I didn't have the fin.close() at the top of the loop but added it when the loop was getting stuck in an infinite loop. I'm thinking that I might have to rename the file variable name each time, i.e.: input_file, input_file2, input_file3...

    Is there a better way?

  2. #2
    root
    Join Date
    Sep 2003
    Posts
    232
    >Is there a better way?
    Code:
    while (!cin.getline(filename) || !fin.open(filename)
      cerr<<File open failure, try again...\n";

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some help with C program writing
    By The_PC_Gamer in forum C Programming
    Replies: 9
    Last Post: 02-12-2008, 09:12 PM
  2. for loop with sort issues
    By redmondtab in forum C Programming
    Replies: 10
    Last Post: 10-09-2006, 10:36 AM
  3. vectors and user input
    By Chaplin27 in forum C++ Programming
    Replies: 6
    Last Post: 01-17-2005, 10:23 AM
  4. comparing user input
    By lambs4 in forum C Programming
    Replies: 5
    Last Post: 12-15-2002, 10:28 AM
  5. Format User Input When using strings
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 03-08-2002, 03:59 AM