I'm totally new in c++ and having problem with a particular portion of my program. As no one to help me in real, I have dared to ask it here. If a text file includes this line "hELp mE", it should be rewritten/overwritten as "HelP Me" in the same exact text file. What i know is that, I might need to use ofstream for the overwriting but i'm very confused about how it should be done. I have tried for about 2 hours and failed. Here is my half completed code which is only able to read from the 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;
}
It's works good:
#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 simply just close() your read mode and open open() mode & take the sentence
this link is may be help to you Input/output with files in C++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With