string line;
string filename;
cout << "Please enter filename :" << endl;
cin >> filename;
ifstream myfile(filename);
/*cout << "Please enter the name of file that you write results : "<< endl;
cin >> wfile; */
if(myfile.is_open())
{
while(getline(myfile,line))
{
convert(line);
}
//getline(myfile,line);
//pushintoVector(line,buffer);
}
else
{
cout << "Error : File could not be opened" << endl;
}
try{
myfile.close();
myFile.close();
}catch(exception &e1)
{
cout << endl;
}
//system("PAUSE");
return 0;
After that i want to send current line to another function like:
void convert(string lines)
{
myFile.open("yazici.txt");
string buf;
string convertingnum;
istringstream ss(lines);
while(ss >> buf)
{
So how can i read word from a line and change it according to if-else structure and write it another file.Edit: Also is there a function or method to determine line length ?
Open the output file at the same time you open the input file.
Pass the output stream as an argument to convert instead of opening the file every time in the function.
Use better names than myfile and myFile.
ifstream inputFile(filename);
ofstream outputFile("yazici.txt");
if(inputFile.is_open())
{
while(getline(inputFile,line))
{
convert(outputFile, line);
}
}
and ...
void convert(std::ostream& outputFile,
string lines)
{
string buf;
string convertingnum;
istringstream ss(lines);
while(ss >> buf)
{
outputFile << buf << std::endl; //???
}
}
Related
I need to delete all the occurencies of a string in a file.
I receive the text as a string and erase every occurencies.
After I deleted all the occurencies i don't know how to save the string back to the file.
I've tried to close the file and wit ofstream to write in it but it didn't work.
#include <iostream>
#include <fstream>
#include <string>
int main () {
std::string file_contents = "";
std::ifstream myfile ("text.txt");
char ch;
if (myfile.is_open())
{
// READ FILE CONTENTS AS STRING
while ( myfile >> std::noskipws >> ch)
{
file_contents += ch;
}
// DISPLAY STRING
std::cout << file_contents << '\n';
// GET WORD TO BE DELETED
std::string word;
std::cout << "Please enter word to be deleted: ";
std::cin >> word;
std::string::size_type found;
std::string new_text;
//DELETE WORD FROM STRING
bool ok=0;
do{
found = file_contents.find(word);
ok=1;
if (found!=std::string::npos)
{
std::cout << word << " found at: " << found << '\n';
file_contents.erase(found, word.length());
std::cout << file_contents << '\n';
}
else
ok==0;
new_text=file_contents;
}while(ok==1);
myfile.close();
}
else std::cout << "Unable to open file";
return 0;
}
Okay so you must close ifstream instance before proceeding to write to the file again.
After closing the file, modify the content and then open the same file for write using ofstream and simply write the content.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string file_contents = "";
std::ifstream myfile("text.txt");
char ch;
if (myfile.is_open())
{
// READ FILE CONTENTS AS STRING
while (myfile >> std::noskipws >> ch)
{
file_contents += ch;
}
myfile.close();
}
else {
std::cout << "Unable to open file";
return -1; // no need to continue if can't read it
}
// DISPLAY STRING
std::cout << file_contents << '\n';
// GET WORD TO BE DELETED
std::string word;
std::cout << "Please enter word to be deleted: ";
std::cin >> word;
//DELETE WORD FROM STRING
size_t found;
while ((found = file_contents.find(word)) != file_contents.npos)
{
std::cout << word << " found at: " << found << '\n';
file_contents.erase(found, word.length());
std::cout << file_contents << '\n';
}
// this will open in text mode and will replace all existing content
std::ofstream out("text.txt");
if (out.is_open()) {
out << file_contents;
out.close();
}
else {
std::cout << "Unable to open file for writing.\n";
return -2; // for failure to open for write
}
return 0;
}
Note: the loop you had went infinitely when I tried to execute it, I had to change it to the code shown above. Also, new_text is completely unnecessary, why have it?
The simpliest way is first to open as input stream. When finish open as output stream to write. It is not the only way you can do that.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
std::string file_contents = "";
{
std::ifstream myfile ("text.txt");
if (! myfile.is_open())
{
else std::cout << "Unable to open file";
return 1;
}
// READ FILE CONTENTS AS STRING
char ch;
while ( myfile >> std::noskipws >> ch) file_contents += ch;
myfile.close();
}
{
std::string word;
std::cin >> word; // GET WORD TO BE DELETED
std::string::size_type found;
while((found = file_contents.find(word))!=std::string::npos)
file_contents.erase(found, word.length());
std::ofstream myfile ("text.txt");
myfile << file_contents<< std::flush;
myfile.close();
}
return 0;
}
I am trying to read a text-file based using the >> stream operator, but this seems to read the file word by word:
void printFile(char filename[])
{
ifstream input;
input.open(filename);
char output[50];
if (input.is_open()) {
while (!input.eof()) {
input >> output;
cout << output << endl;
}
}
else cout << "File is not open!";
input.close();
cout << endl;
}
The only problem with this is that it won't print out the linebreaks.
Please note that I'm still learning C++ and the goal is to achieve this without using strings (so without getline). Is there any way of doing this, or is it simply impossible?
Thanks to #odin I found the solution by reading the file by character instead of by word:
void printFile(char filename[])
{
char ch;
fstream fin(filename, fstream::in);
while (fin >> noskipws >> ch) {
cout << ch;
}
fin.close();
}
You can identify an end of a line as follow
int main(){
char ch;
fstream fin("filename.txt", fstream::in);
while(fin >> noskipws >> ch){
if(ch == '\n') { // detects the end of the line
cout << "This is end of the line" << endl;
}
}
return 0;
}
I'm trying to print the contents of the file to output but the output is missing the spaces from the file.
I've also tried using infile >> noskipws >> ch; but it displays only the first word from the file.
int process_infile(int shift)
{
char c[1000];
ifstream ifile;
ifile.open("D:\\example.txt") ;
if(!ifile)
{
//cout<<"Error in opening file..!!";
error();
//getch();
exit(1);
}
cout<<"Data in file = ";
while(ifile.eof()==0)
{
ifile >> c;
cout << c;
//encodeCaesarCipher(c,shift);
}
ifile.close();
getch();
return 1;
}
try
while(ifile.eof()==0)
{
string line;
getline(ifile,line);
cout << line;
//encodeCaesarCipher(c,shift);
}
Final project for programming class due tomorrow, any help appreciated, program crashes in this module, after accepting file name. By crash I mean it outputs "This application has requested runtime to terminate it in an unusual way" and then the usual windows "CotD.exe has stopped working":
void load(vector<Fish>& stock)
{
char c;
do {
cout << "Welcome to Catch of The Day, enter (f) to choose a file to load from, otherwise enter anything else to load from default file.\n";
cin >> c;
if (c == 'f' || c == 'F')
{
cout << "Enter file name\n";
cin >> file;
}
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << " Check the directory location of CotD.exe and try again\n";
}
else
{
while (!fin.eof())
{
Fish f;
string blank;
fin >> f.amt;
fin >> f.prc;
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(fin, blank);
stock.push_back(f);
}
fin.close();
break;
}
} while (true);
}
EDIT other relevant code:
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
using namespace std;
//
string file = "default.txt"; //Global variable used to store name of save file.
//It is global so that load() and save() can both access it.
struct Fish
{
string type;
double amt;
double prc;
double val;
};
void addType(vector<Fish>&);
void editStock(vector<Fish>&);
void sortBy(vector<Fish>&);
void sortAsc(vector<Fish>&,char);
void sortDesc(vector<Fish>&,char);
void display(vector<Fish>&);
int search(vector<Fish>&);
void save(vector<Fish>&);
void load(vector<Fish>&);
string getType();
int dispType(string,vector<Fish>&);
int find(string,vector<Fish>&);
double getAmt();
void delType(string,vector<Fish>&);
void menu(vector<Fish>&);
double getPrc();
int main(){
std::vector<Fish> stock;
load(stock);
menu(stock);
save(stock);
cout<<endl<<endl
<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
<<"|Thank you for using Catch of the Day|\n"
<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
system("Pause");
return 0;
}
I recently wrote this program which seems very similar to me, and ran perfectly I can't see the difference:
void load(vector<string>& names)
{
string file, name, bad;
while (true)
{
cout << "Input file name\n";
getline(cin, file);
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << ", try again.\n";
}
else break;
}
ifstream fin(file.c_str());
while (!fin.eof())
{
fin >> bad;
fin >> name;
cout << "\"" << name << "\"" << endl;
}
system("Pause");
fin.close();
ifstream fin(file.c_str());
while (!fin.eof())
{
getline(fin, name);
names.push_back(name);
}
system("Pause");
fin.close();
cout << "Names added to list\n";
}
I've edited your code, this is what I got:
void load(vector<Fish>& stock)
{
char c;
do {
cout << "Welcome to Catch of The Day, enter (f) to choose a file to load from, otherwise enter anything else to load from default file.\n";
cin >> c;
if (c == 'f' || c == 'F')
{
cout << "Enter file name\n";
cin >> file;
}
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << " Check the directory location of CotD.exe and try again\n";
}
else
{
Fish f;
string blank;
if (fin>>f.amt)
{
if (fin>>f.prc)
{
getline(fin,blank);
stock.pushback(f);
}
}
fin.close();
break;
}
} while (true);
}
Of course, this is without knowing what is in the file and what the heck Fish is, so I do not know if this is what you are looking for.
EDIT:If you could include the file, or just a section of one "fish" as I assume that is what the contents of the file are, it would be alot easier to help.
Something is definitely wrong with my loop because after reading and executing the first line the programs ends.
if (infile.is_open())
{
cout << "Input filename: ";
cin>>filename;
infile.open(filename.c_str());
cout<< "Output filename: ";
cin>>filename;
outfile.open(filename.c_str());
while(getline(infile,input))
{
string output = "";
for(int x = 0; x < input.length(); x++)
output += cipher(input[x]);
cout<<output<<endl;
outfile<<output;
}
}
Any suggestions on how to make this work?
EDIT
Followed the suggestions and got this:
if (infile.is_open()) {
cout << "Input filename: ";
cin>>filename;
infile.open(filename.c_str());
if (!infile.is_open())
{
std::cout << "Failed to open the input file." << std::endl;
return -1;
}
cout<< "Output filename: ";
cin>>filename;
outfile.open(ofilename.c_str());
if (!outfile.is_open())
{
std::cout << "Failed to open the output file." << std::endl;
return -1;
}
while(getline(infile,line)){
string output = "";
for(int x = 0; x < input.length(); x++) {
output += cipher(input[x]);
}
}
BUT it still reads only the first line...everything else is working perfectly fine....just can't read anything beyond the first line..
It seems that you misunderstood the point of the fstream's is_open() method, since this code:
if (infile.is_open())
{
cout << "Input filename: ";
cin>>filename;
infile.open(filename.c_str());
...
}
checks whether the infile has been successfully opened (i.e. if either a previous call to member open succeeded or if the object was successfully constructed using the parameterized constructor,
and close has not been called since) and in case it is open it retrieves the name of the input file from cin and opens the file.
Good start would be the program that reads from the input file line by line and writes these lines to the output file without processing them:
// retrieve the name of the input file and open it:
cout << "Input filename: ";
cin>>filename;
infile.open(filename.c_str());
if (!infile.is_open())
{
std::cout << "Failed to open the input file." << std::endl;
return -1;
}
// retrieve the name of the output file and open it:
cout << "Output filename: ";
cin >> filename;
outfile.open(filename.c_str());
if (!outfile.is_open())
{
std::cout << "Failed to open the output file." << std::endl;
return -1;
}
std::string line;
while(getline(infile,line))
{
std::cout << line << std::endl;
outfile << line;
}
So I suggest this.
Write char cipher(char ch) to return enciphered input for anything. if you don't want to encipher whitespace, then don't. But always return the enciphered character or unmodifed character.
Use std::transform , std::istream_iterator , and std::ostream_iterator to transform your input and output files.
Check your file states at the correct times.
An example appears below:
#include <iostream>
#include <fstream>
#include <iteraor>
#include <string>
using namespace std;
char cipher(char ch)
{
if (std::isalpha(ch))
{
// TODO: change ch to whatever you want here.
}
// but always return it, whether you changed it or not.
return ch;
}
int main()
{
int res = EXIT_SUCCESS;
string in_filename, out_filename;
cout << "Input filename: ";
cin >> in_filename;
cout << "Output filename: ";
cin >> out_filename;
// don't skip whitespace
ifstream infile(in_filename);
ofstream outfile(out_filename);
if ((infile >> noskipws) && outfile)
{
std::transform(istream_iterator<char>(infile),
istream_iterator<char>(),
ostream_iterator<char>(outfile),
cipher);
}
else
{
perror("Failed to open files.");
res = EXIT_FAILURE;
}
return res;
}