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++
Follow #πάντα ῥεῖ solution, you could using ifstream to read the contents in the specific file, then judge and change UPPER/lower for every character. At the end, using ofstream to overwrite the original file.
Wish is helpful.
You can use fstream to do in-place rewriting in C++. This will replace all lowercase with uppercase 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;
}
Related
I want to extract c-keywords from my given input text file (which is a sample c code) and output them into a separate text file one word per line. How can i get this? Please help me. My code is given below:
#include <iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
ifstream My_input_file("D:\\input.txt");
ofstream My_output_file("D:\\output.txt");
string line, temp;
int flag=1;
if(My_input_file.is_open())
{
while(getline(My_input_file,line))
{
int lenth=line.length(),i;
char* newline = new char[lenth+1];
strcpy(newline,line.c_str());
for(i=0; i<lenth; i++)
{
if(newline[i]=='/'&& newline[i+1]=='/')
break;
if (newline[i]=='/'&& newline[i+1]=='*')
flag=2;
if (newline[i]=='*'&& newline[i+1]=='/')
{flag=1;
i++;}
else if(flag==1)
My_output_file<<newline[i];
}
My_output_file<<"\n";
for(i=0;i<lenth;i++)
{
if(newline[i]=' ')
{
if(temp=="auto"||temp=="double"||temp=="int"||temp=="struct"||temp=="break"||temp=="else"||temp=="long"||temp=="switch"||temp=="case"||temp=="enum"||temp=="register"||temp=="typedef"||temp=="char"||temp=="extern"||temp=="return"||temp=="union"||temp=="const"||temp=="float"||temp=="short"||temp=="unsigned"||temp=="continue"||temp=="for"||temp=="signed"||temp=="void"||temp=="default"||temp=="goto"||temp=="sizeof"||temp=="volatile"||temp=="do"||temp=="if"||temp=="static"||temp=="while")
My_output_file<<newline[i];
}
else
{
temp+=newline[i];
}
}
}
}
return 0;
}
I want to extract the c keyword like word from my input text file and generate the matching word in a output text file. But my program just avoiding comment line. It does not write the matched word what i searched for.
If my input.txt file contains some text like a c++ code for prime number check with comment line
Then output.txt file should be look like:
The Whole prime number code Without comment line
Matched keyword list is:
Int
float
double
return
After editing my code i have find out a solution for lexical analysis. The edited code is looks like this:
#include <iostream>
#include<fstream>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
using namespace std;
int isKeyword(char buffer[]){
char keywords[32][10] = {"auto","break","case","char","const","continue","default",
"do","double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"};
int i, flag = 0;
for(i = 0; i < 32; ++i){
if(strcmp(keywords[i], buffer) == 0){
flag = 1;
break;
}
}
return flag;
}
int main()
{
ifstream My_input_file("D:\\input.txt");
ifstream My_library_file("D:\\library.txt");
ofstream My_output_file("D:\\output.txt");
string line, temp;
int flag=1;
if(My_input_file.is_open())
{
while(getline(My_input_file,line))
{
int lenth=line.length(),i;
char* newline = new char[lenth+1];
strcpy(newline,line.c_str());
for(i=0; i<lenth; i++)
{
if(newline[i]=='/'&& newline[i+1]=='/')
break;
if (newline[i]=='/'&& newline[i+1]=='*')
flag=2;
if (newline[i]=='*'&& newline[i+1]=='/')
{flag=1;
i++;}
else if(flag==1)
My_output_file<<newline[i];
}
My_output_file<<"\n";
}
My_output_file<<endl<<"Keywords Found in Your Text";
My_output_file<<endl<<"-------------------------------------"<<endl;
cout<<"Keyword Found in Your Text"<<endl;
cout<<"-------------------------------------"<<endl;
char ch, buffer[15];
ifstream fin("D:\\input.txt");
int j=0;
if(!fin.is_open()){
cout<<"error while opening the file\n";
exit(0);
}
while(!fin.eof()){
ch = fin.get();
if(isalnum(ch)){
buffer[j++] = ch;
}
else if((ch == ' ' || ch == '\n') && (j != 0)){
buffer[j] = '\0';
j = 0;
if(isKeyword(buffer) == 1)
cout<<buffer<<"\n";
}
}
}
return 0;
}
But now it is output a text file without comment line and the founded keyword list in a console window. I want to output the keyword list in my output.txt file.
My input.txt is like this:
input.txt
My Output Should be look like this:
output.txt
But it output a text file like this:
After Clicking Build and Run the output
and the console showing the founded keyword list like this:
After Build and Run the console
But, I want to put the founded keyword list into output.txt file instead of the console display.
Then i have changed these code:
if(isKeyword(buffer) == 1)
cout<<buffer<<"\n";
with this
My_output_file<<buffer[j]<<"\n";
Then i got my solution near about. But it output the first word of the keyword. How can i get the full word?
I know this is a dumb question!
But I just CAN NOT get my head around how to read my file into an array one word at a time using c++
Here is the code for what I was trying to do - with some attempted output.
void readFile()
{
int const maxNumWords = 256;
int const maxNumLetters = 32 + 1;
int countWords = 0;
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
string word;
while (fin >> word)
{
countWords++;
assert (countWords <= maxNumWords);
}
char listOfWords[countWords][maxNumLetters];
for (int i = 0; i <= countWords; i++)
{
while (fin >> listOfWords[i]) //<<< THIS is what I think I need to change
//buggered If I can figure out from the book what to
{
// THIS is where I want to perform some manipulations -
// BUT running the code never enters here (and I thought it would)
cout << listOfWords[i];
}
}
}
I am trying to get each word (defined by a space between words) from the madLib.txt file into the listOfWords array so that I can then perform some character by character string manipulation.
Clearly I can read from a file and get that into a string variable - BUT that's not the assignment (Yes this is for a coding class at college)
I have read from a file to get integers into an array - but I can't quite see how to apply that here...
The simplest solution I can imagine to do this is:
void readFile()
{
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
vector<string> listOfWords;
std::copy(std::istream_iterator<string>(fin), std::istream_iterator<string>()
, std::back_inserter(listOfWords));
}
Anyways, you stated in your question you want to read one word at a time and apply manipulations. Thus you can do the following:
void readFile()
{
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
vector<string> listOfWords;
string word;
while(fin >> word) {
// THIS is where I want to perform some manipulations
// ...
listOfWords.push_back(word);
}
}
On the suggestion of πάντα ῥεῖ
I've tried this:
void readFile()
{
int const maxNumWords = 256;
int const maxNumLetters = 32 + 1;
int countWords = 0;
ifstream fin;
fin.open ("madLib.txt");
if (!fin.is_open()) return;
string word;
while (fin >> word)
{
countWords++;
assert (countWords <= maxNumWords);
}
fin.clear();
fin.seekg(0);
char listOfWords[countWords][maxNumLetters];
for (int i = 0; i <= countWords; i++)
{
while (fin >> listOfWords[i]) //<<< THIS did NOT need changing
{
// THIS is where I want to perform some manipulations -
cout << listOfWords[i];
}
}
and it has worked for me. I do think using vectors is more elegant, and so have accepted that answer.
The suggestion was also made to post this as a self answer rather than as an edit - which I kind of agree is sensible so I've gone ahead and done so.
The most simple way to do that is using the STL algorithm... Here is an example:
#include <iostream>
#include <iomanip>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> words;
auto beginStream = istream_iterator<string>{cin};
auto eos = istream_iterator<string>{};
copy(beginStream, eos, back_inserter(words));
// print the content of words to standard output
copy(begin(words), end(words), ostream_iterator<string>{cout, "\n"});
}
Instead of cin of course, you can use any istream object (like file)
When i read from a file string by string, >> operation gets first string but it starts with "i" . Assume that first string is "street", than it gets as "istreet".
Other strings are okay. I tried for different txt files. The result is same. First string starts with "i". What is the problem?
Here is my code :
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int cube(int x){ return (x*x*x);}
int main(){
int maxChar;
int lineLength=0;
int cost=0;
cout<<"Enter the max char per line... : ";
cin>>maxChar;
cout<<endl<<"Max char per line is : "<<maxChar<<endl;
fstream inFile("bla.txt",ios::in);
if (!inFile) {
cerr << "Unable to open file datafile.txt";
exit(1); // call system to stop
}
while(!inFile.eof()) {
string word;
inFile >> word;
cout<<word<<endl;
cout<<word.length()<<endl;
if(word.length()+lineLength<=maxChar){
lineLength +=(word.length()+1);
}
else {
cost+=cube(maxChar-(lineLength-1));
lineLength=(word.length()+1);
}
}
}
You're seeing a UTF-8 Byte Order Mark (BOM). It was added by the application that created the file.
To detect and ignore the marker you could try this (untested) function:
bool SkipBOM(std::istream & in)
{
char test[4] = {0};
in.read(test, 3);
if (strcmp(test, "\xEF\xBB\xBF") == 0)
return true;
in.seekg(0);
return false;
}
With reference to the excellent answer by Mark Ransom above, adding this code skips the BOM (Byte Order Mark) on an existing stream. Call it after opening a file.
// Skips the Byte Order Mark (BOM) that defines UTF-8 in some text files.
void SkipBOM(std::ifstream &in)
{
char test[3] = {0};
in.read(test, 3);
if ((unsigned char)test[0] == 0xEF &&
(unsigned char)test[1] == 0xBB &&
(unsigned char)test[2] == 0xBF)
{
return;
}
in.seekg(0);
}
To use:
ifstream in(path);
SkipBOM(in);
string line;
while (getline(in, line))
{
// Process lines of input here.
}
Here is another two ideas.
if you are the one who create the files, save they length along with them, and when reading them, just cut all the prefix with this simple calculation: trueFileLength - savedFileLength = numOfByesToCut
create your own prefix when saving the files, and when reading search for it and delete all what you found before.
I saved this word "abs" in a text file and i'm trying to make a code that can print the three characters at once in another file .. not like that
while (content[i] == 'a')
{
fout<<"a";
break;}
while (content[i] == 'b')
{
fout<<"b";
break;}
while (content[i] == 's')
{
fout<<"s";
break;}
here is the code i wrote but it doesn't print anything out..
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fout("E:\\hoss.txt");
ifstream file("E:\\test.txt");
string content;
while(file >> content)
{
for (size_t i = 0; i < content.size(); i++)
{
while (content[i] == 'ab')
{
fout<<"ab";
break;}
}}
system("pause");
return 0;
}
anyone can help??
int main()
{
ofstream fout("E:\\hoss.txt");
ifstream file("E:\\test.txt");
string content;
while(file >> content)
{
for (size_t i = 0; i < content.size(); i++)
{
if((content[i] == 'a') && (content[i+1] == 'b'))
{
fout<<"ab";
break;
}
}
}
system("pause");
return 0;
}
You have no code to print anything out. You just keep adding to the buffer, but you never flush the buffer. Get rid of the system("pause"); and just let the program end. Ending the program flushes all buffers.
while (content[i] == 'ab')
This is pretty baffling. Did you really mean ab as a character constant?
When i read from a file string by string, >> operation gets first string but it starts with "i" . Assume that first string is "street", than it gets as "istreet".
Other strings are okay. I tried for different txt files. The result is same. First string starts with "i". What is the problem?
Here is my code :
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int cube(int x){ return (x*x*x);}
int main(){
int maxChar;
int lineLength=0;
int cost=0;
cout<<"Enter the max char per line... : ";
cin>>maxChar;
cout<<endl<<"Max char per line is : "<<maxChar<<endl;
fstream inFile("bla.txt",ios::in);
if (!inFile) {
cerr << "Unable to open file datafile.txt";
exit(1); // call system to stop
}
while(!inFile.eof()) {
string word;
inFile >> word;
cout<<word<<endl;
cout<<word.length()<<endl;
if(word.length()+lineLength<=maxChar){
lineLength +=(word.length()+1);
}
else {
cost+=cube(maxChar-(lineLength-1));
lineLength=(word.length()+1);
}
}
}
You're seeing a UTF-8 Byte Order Mark (BOM). It was added by the application that created the file.
To detect and ignore the marker you could try this (untested) function:
bool SkipBOM(std::istream & in)
{
char test[4] = {0};
in.read(test, 3);
if (strcmp(test, "\xEF\xBB\xBF") == 0)
return true;
in.seekg(0);
return false;
}
With reference to the excellent answer by Mark Ransom above, adding this code skips the BOM (Byte Order Mark) on an existing stream. Call it after opening a file.
// Skips the Byte Order Mark (BOM) that defines UTF-8 in some text files.
void SkipBOM(std::ifstream &in)
{
char test[3] = {0};
in.read(test, 3);
if ((unsigned char)test[0] == 0xEF &&
(unsigned char)test[1] == 0xBB &&
(unsigned char)test[2] == 0xBF)
{
return;
}
in.seekg(0);
}
To use:
ifstream in(path);
SkipBOM(in);
string line;
while (getline(in, line))
{
// Process lines of input here.
}
Here is another two ideas.
if you are the one who create the files, save they length along with them, and when reading them, just cut all the prefix with this simple calculation: trueFileLength - savedFileLength = numOfByesToCut
create your own prefix when saving the files, and when reading search for it and delete all what you found before.