I've already written a good size program, for a slight beginner.
Part of what I've done, is that it will look to see if my file "Namefile.txt" is open, if it is and it isnt at eof, it will extract the name within the txt and import it into a sentence. "Welcome back, *name*."
It works just like I want it to, if the text document is already created.
I'm trying and failing on initially creating the file, if it doesnt exist but skipping to the rest of my code if it does exist.
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
|
string name;
ifstream ifName;
ofstream noName;
ifName.open ("Namefile.txt");
if (ifName.is_open())
{
ifName >> name;
if (!ifName.eof())
{
ifName >> name;
cout << "Welcome back, " << name << "." << endl;
ifName.close();
}
else if(ifName.eof())
{
ifName.close();
noName.open("Namefile.txt", ios::app);
cout << "Please enter your name: ";
getline (cin, name);
noName << name << endl;
noName.close();
}
else
cout << "Cannot open file." << endl;
}
|
That is the section that I'm working on.
I've found that when I use,
noName.open();, it creates the text file named Namefile, as I desire.
But, if I add the, noName.open();, before the, ifName.open();, it will ask for a name every compile, no matter if I leave the noName open or if I close it before or after the, ifName, is opened.
If I'm a bit confusing, sorry.
Again, the code that I showed above works perfectly; IF the text document is already created. im trying to create the file before the already shown code so that the shown code will work without having to initially manually create the Namefile text document. lol
Any help would be much appreciated! Thank you.