我正在尝试使程序提示用户输入文件名,然后提示用户输入要删除的单词。 有没有没有在main外部进行任何功能的方法? (提前致谢!) 到目前为止,这是我的代码:
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;
}
答案 0 :(得分:0)
XXXX
如果输入char fileName = ' ';
,则循环不会退出。它将尝试处理其余代码。
std::string fileName;
声明一个字符。您需要一个字符数组。更好的是,将其声明为remove(fileName + ".txt");
remove
无法编译,因为std::string
是C函数。 C不支持类,也不知道如何处理诸如fileName.c_str()
之类的类。您想提供一个C字符串,您可以使用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;
}
}
}
来完成,以下是一些建议:
num