gpt4 book ai didi

c++ - 如何重写/覆盖文本文件中的字符串/行?

转载 作者:太空狗 更新时间:2023-10-29 23:01:14 25 4
gpt4 key购买 nike

我是 c++ 的新手,我的程序的特定部分有问题。由于没有人真正帮助我,所以我才敢在这里问。如果文本文件包含此行“hELp mE”,则应在同一文本文件中将其重写/覆盖为“HelP Me”。我所知道的是,我可能需要使用 ofstream 进行覆盖,但我很困惑应该如何完成。我已经尝试了大约 2 个小时,但失败了。这是我完成了一半的代码,它只能从文件中读取。

 int main()
{
string sentence;
ifstream firstfile;
firstfile.open("alu.txt");
while(getline(firstfile,sentence))
{
cout<<sentence<<endl;
for(int i=0;sentence[i] !='\0';i++)
{
if((sentence[i] >='a' && sentence[i] <='z') || (sentence[i] >='A' && sentence[i] <='Z'))
{

if(isupper(sentence[i]))
sentence[i]=tolower(sentence[i]);
else if(islower(sentence[i]))
sentence[i]=toupper(sentence[i]);
}
}
}


return 0;
}

最佳答案

效果不错:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string sentence;
ifstream firstfile;
firstfile.open("alu.txt");
while(getline(firstfile,sentence))
{
cout<<sentence<<endl;
for(int i=0; sentence[i] !='\0'; i++)
{
if((sentence[i] >='a' && sentence[i] <='z') || (sentence[i] >='A' && sentence[i] <='Z'))
{

if(isupper(sentence[i]))
sentence[i]=tolower(sentence[i]);
else if(islower(sentence[i]))
sentence[i]=toupper(sentence[i]);
}
}
}
firstfile.close();
cout<<sentence<<endl;
ofstream myfile;
myfile.open ("alu.txt");
myfile<<sentence;
myfile.close();

return 0;
}

根据你的代码,我只是简单地close()你的阅读模式并打开open()模式&采取语句

此链接可能对您有帮助Input/output with files in C++

关于c++ - 如何重写/覆盖文本文件中的字符串/行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636394/

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