gpt4 book ai didi

c++从.txt文件中删除行

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:11:21 25 4
gpt4 key购买 nike

我正在尝试从我的 .txt 文件中删除一行。该文件包含有关帐户的所有信息。

该行显示“newAccount”,是在创建帐户时生成的。我使用它以便在您首次登录时启动教程。教程结束后我想删除此行,以便在下次登录时您不会获得教程。

这是一段代码:(不起作用)

void loginScreen(string user){
system("CLS");
cout << "Hello " + user << endl;

ifstream file(user + ".txt");
string line1;
getline(file, line1);
// Begin reading your stream here
string line2;
getline(file, line2);

if(line2 == "newAccount"){
cout << "Your account is new";

char cUser[200];

strcpy_s(cUser, user.c_str());

std::ofstream newFile( user + ".txt.new" );
// Do output...!!!!!!!
newFile << line1;
newFile.close();
if ( newFile ) {
remove( cUser + ".txt" );
rename( cUser + ".txt", cUser + ".txt" );
} else {
std::cerr << "Write error on output" << std::endl;
}
}

}

编辑:

我已经为此编辑了我的代码,但它仍然不起作用:

const string oldFileName(user + ".txt");
const string newFileName(user + ".txt.new");

std::ofstream newFile( user + ".txt.new" );
// Do output...!!!!!!!
newFile << line1;
newFile.close();


if(line2 == "newAccount"){
ofstream newFile(newFileName.c_str()); // c++11 allows std::string
if (newFile){
if (0 == remove( oldFileName.c_str() )){
if (0 != rename( newFileName.c_str(), oldFileName.c_str() )){
// Handle rename failure.
}
}else{
// Handle remove failure.
}
}

最佳答案

这个:

rename( cUser + ".txt", cUser + ".txt" );

不正确的原因有两个:

  1. 它是指针算法而不是字符串连接,因为 cUser 是一个 char[]
  2. 即使拼接正确,旧文件名和新文件名也相同

没有理由使用strcpy_s(),对std::string使用operator+:

const std::string oldFileName(user + ".txt");
const std::string newFileName(user + ".txt.new");

std::ofstream newFile(newFileName.c_str()); // c++11 allows std::string
if (newFile && newFile << line1)
{
newFile.close();
if (newFile)
{
if (0 == remove( oldFileName.c_str() ))
{
if (0 != rename( newFileName.c_str(), oldFileName.c_str() ))
{
// Handle rename failure.
}
}
else
{
// Handle remove failure.
}
}
}

在尝试 remove() 之前,请记住 file.close()

始终检查 IO 操作的结果,代码不确认 file 是否打开或任何 getline() 尝试是否成功:

ifstream file(user + ".txt");
if (file.is_open())
{
string line1, line2;
if (getline(file, line1) && getline(file, line2))
{
// Successfully read two lines.
}
}

关于c++从.txt文件中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16518431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com