Ok this topic may make no sense at first but here's the code I'm having trouble with.
Ok heres what is happening with this code when compiled and ran. It is able to tell me the file exists and will ask for input of a dif file name (so getting into the loop works fine).Code:#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ............................. while(!savefile.is_open()) { cout << "Please give me a name." << endl; getline(cin, name, '\n'); fstream savefile (name.c_str(), ios_base::in); //To check if file exists if(!savefile) //If file doesn't exist, create it. ofstream savefile (name.c_str()) else //If file does exist loop back and ask for dif name cout << "Name already in use. Please choose another name." << endl; .................................... }
The problem is when i give it a name that doesn't exist. It'll take the name and create the folder yet it'll loop back to asking for a name again rather then breaking the loop. It'll do this no matter how many times i give it a new name.
Heres what I have tried.
I've tried making sure the file is open with savefile.open(name.cstr()) (still loops after new name entered).
I've tried the condition for while to be !savefile.
I've tried a do while loop with condition being both !savefile and !savefile.is_open()
I can't remember much else but I'm sure my problem relys in the condition and can probable be fixed with an extra in variable. Kinda like this.
I have thought of this fix but am tring to find a fix that does not cause unnecessary variable.Code:int x = 0; //new variable while(x!=1) { cout << "Please give me a name." << endl; getline(cin, name, '\n'); fstream savefile (name.c_str(), ios_base::in); //To check if file exists if(!savefile) { //If file doesn't exist, create it. ofstream savefile (name.c_str()) x=1; } else { //If file does exist loop back and ask for dif name cout << "Name already in use. Please choose another name." << endl; x=0; }
Thanks for any help in advance.



LinkBack URL
About LinkBacks



