loop help

Write your question here.
So i have to write a program and one requiremnt is that I have to implement this

If the file has not been opened correctly, print the following message then go back to step 1 and re-prompt for the file name. Re-prompt a maximum of 2 times. (prompt a maximum of 3 times)
ERROR: File FILENAME could not be opened for input
NOTE: in this message FILENAME will be replaced with the input filename provided by the user
If all 3 tries fail print the message
ERROR: You exceeded maximum number of tries allowed
while entering the input file name

this is what i have so far

cout << "Type the name of the input file containing sensor readings: " << endl;
cin >> inputName;
inFile.open(inputName);
if (!inFile.open(inputName)


cerr << "ERROR: File" << inputName << "could not be opened for input";
loop

please help me, been stuck for hours
Your code looks ok, you just need to put it into a loop.
Maybe like this:
1
2
3
4
5
6
7
8
9
10
11
  const int MAX_TRIALS = 3;
  int num_trials = 0;
  bool file_opened = false;
  while(num_trials < MAX_TRIALS && !file_opened)
  {
    // increment num_trials
    // prompt to enter the filename
    // read the file name
    // if file opens set file_opened to true
    // else print error msg
  }
Hello ineedhelp2,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

It makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.

Given a file name of "File Name", notice the space, cin >> inputName; will only input up to and including the first white space leaving "Name" in the input buffer for the next "cin >>" or whatever is used. If the file name happens to be "FileName" this will work fine.

I suggest using std::getline(std::cin", inputName) for the best results.

Then the lines:
1
2
inFile.open(inputName);
if (!inFile.open(inputName)

You are trying to open the same file stream twice. What I see most often is: if (!inFile) will suffice. And you are missing a closing parenthesis on your code not that it makes much difference.

An implementation of Thomas1965's loop will work here.

Something else to think about. Will the user be entering the complete file name with extension or will the program need to provide the extension?

One last point it is generally better to post the whole code that can be compiled as there may be other problems that may need addressed.

Hope that helps,

Andy
Topic archived. No new replies allowed.