I'm trying to make it so the program prompts the user for the name of the file, then prompt them for what word they'd like to be removed. Is there a way to do so without making any functions outside from main? (Thanks in advance!) Here's my code so far:
ofstream outFile;
string in;
char in2[800];
char fileName = ' ';
while (in != "XXXX") {
cout << "What do you want to name the file? Enter a name or enter XXXX to quit.\n";
cin >> in;
for (int i = 0; i < in.length(); i++)
{
fileName += in[i];
}
outFile.open(in + ".txt");
if (outFile.fail())
{
outFile << "Can't do it.";
}
else
{
cout << "What do you want in it?\n";
cin >> in2;
cin.getline(in2, sizeof(in2));
outFile << in2;
}
outFile.close();
ifstream reader;
string oneLine;
reader.open(in + ".txt");
if (reader.fail())
{
cout << "Could not read file.\n";
return 0;
}
else
{
reader.clear();
reader.seekg(60L, ios::beg);
getline(reader, oneLine);
cout << "Is there something you'd like to remove from " << in << ".txt?\n";
cin >> in2;
ofstream write("tmp.txt");
while (getline(reader, oneLine)) {
if (oneLine != in2)
write << oneLine << endl;
}
reader.close();
write.close();
remove(fileName + ".txt");
rename("tmp.txt", fileName + ".txt");
return 0;
}
return 0;
}
while (in != "XXXX") { cout << "What do you want to name the file? Enter a name or enter XXXX to quit.\n"; ... }
If you enter XXXX
the loop won't quit. It will try to process the rest of the code.
char fileName = ' ';
declares a single character. You want an array of characters. Better yet, declare it as std::string fileName;
remove(fileName + ".txt");
won't compile because remove
is a C function. C doesn't support classes and it doesn't know what to do with classes such as std::string
. You want to supply a C-string, you can do that with fileName.c_str()
Below are a few suggestions:
int main()
{
ofstream outFile;
string fileName;
string text;
for(;;)
{
cout << "What do you want to name the file?\n";
cout << "Enter a name or enter 999 to quit.\n";
cin >> fileName;
if(fileName == "999")
break;
fileName += ".txt";
outFile.open(fileName);
if(outFile.fail())
{
cout << "Can't do it.";
continue;
}
else
{
for(;;)
{
cout << "What do you want in it?\n";
cout << "Enter a name or enter 999 to stop.\n";
cin >> text;
if(text == "999")
break;
outFile << text << endl;
}
}
outFile.close();
ifstream reader;
reader.open(fileName);
if(reader.fail())
{
cout << "Could not read file.\n";
}
else
{
cout << "Is there something you'd like to remove from " << fileName << "?\n";
cin >> text;
string oneLine;
ofstream write("tmp.txt");
while(getline(reader, oneLine))
{
if(oneLine != text)
write << oneLine << endl;
}
reader.close();
write.close();
remove(fileName.c_str());
rename("tmp.txt", fileName.c_str());
break;
}
}
}