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

标签 c++

我是 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/

相关文章:

c++ - 如何获得一个月中的总天数并忽略周末

c++ - 尝试添加 opencv 库时出现 CMake 错误

java - 将 java 字符串处理为 Android Studio+NDK 的原生 C/C++

c++ - 在 C++ 中更改结构内部元素的方法?

c++ - 为什么 IsValid(Object) 返回 true 后 Object 不能安全使用?

C++ 创建子矩阵

c++ - 着色器中的图像模糊效果

c++ - XAudio2 延迟声音 - 播放多个声音时

C++ 从一个字符中获取指定的部分

c++ - 如何实现 array::max_size()?