How do I rewrite / overwrite lines / lines in a text file?

I am completely new to C ++ and have a problem with a certain part of my program. Since no one could help me in reality, I dared to ask about it here. If the text file includes this line "hELp mE", it should be overwritten / overwritten as "HelP Me" in the same text file. I know what I might need to use ofstream

to rewrite, but I am very confused as to how this should be done. I tried for about 2 hours and it failed. Here is my semi-finished code that can only be read from a file.

 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;
}

      

+3


source to share


3 answers


It works well:

#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;
}

      



according to your code i just just close()

your read mode and open the mode open()

and takesentence

This link may be helpful to you File I / O in C ++

+1


source


Follow @ πάντα ῥεῖ solution, you can use ifstream

to read the content in a specific file, then judge and change UPPER / lower for each character. At the end, using ofstream

to overwrite the original file.



Desire is beneficial.

0


source


You can use the fstream command to perform in-place rewriting in C ++. This will replace all uppercase letters and vice versa, character by character.

#include <iostream>
#include <fstream>
#include <locale>

int main()
{
  std::locale loc;
  std::fstream s("a.txt");
  char next;
  int pos = 0;
  while((next = s.peek()) != EOF) {
    if(islower(next,loc))
      next = toupper(next,loc);
    else if(isupper(next,loc))
      next = tolower(next,loc);
    s.seekp(pos);
    s.write(&next,1);
    pos++;
  }
  return 0;
}

      

0


source







All Articles