Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi all,
before i begin, yes this is an homework assignment question...
got a c++ file I/O question. here is the code that i've so far.
#include <iostream>
#include <sting>
#include <fstream>int main()
{
string inputFileName;ifstream inputFile;
cout << "enter file name";
cin >> inputFileName;inputFile.open (inputFileName.c_str());
// if file fails to open/exist
while(inpuFile == NULL)
{
cout << "enter file name";
cin >> inputFileName;
inputFile.open (inputFileName.c_str());
}
// if the file open successfully, exit loopreturn 0;
}so the purpose is if the input file name entered by the user does not exist or fail to open then keep looping throuh until the file opens.
to test it out, i give the wrong file name so the loop is executed, then i provide the correct file name...it does not open the file and i keep looping through..
i'm probably doing something wrong with ( inputFile == NULL ) condition...please help
thanks in advance
Clicker

You have some of your variables mis-spelled. Need to correct that first... first instance: In your while loop you have
'inpuFile' and not 'inputFile'.---
inFile.open(filename_in.c_str());
Try the following:
fstream has a fail()
cout << "inFile.fail() = "<< inFile.fail() << endl; // fail() = 1 if file exists
OR
if(!inFile)
{...}
IR

Close but you need to clear the fail bit. After the fail bit is set even a success will not clear it.
while(inputFile.fail())
{
inputFile.clear();
cout << "enter file name";
cin >> inputFileName;
inputFile.open (inputFileName.c_str());
}

Looks like a typo but your second include call in the program calls sting...you probably meant string
#include <string>
~Tugg~

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |