replacing an entire line in from a file C++ - c++

So I've been playing with code and I'm stuck with finding how to replace the line found. I'm able to find the name and add the 'new_gpa' to the section but it outputs the final result in the same file but without replacing the original score and name.
how could I remove the original line found along with the gpa? and also store the new values to the file.
cristian 2.1
rachel 3.0
name search: cristian
new file:
cristian 2.1
rachel 3.0
cristian 4.1
The code is below.
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <sstream>
#include <cstring>
using namespace std;
int main()
{
string name;
int offset;
string line;
ifstream read_file;
read_file.open("alpha.dat", std::ios_base::app);
cout << "Please enter your name: \n";
cin>> name;
if (read_file.is_open())
{
while(!read_file.eof())
{
getline(read_file,line);
if((offset = line.find(name)) != string::npos)
{
cout <<"the word has been found: \n";
//cout << line //example to display
//new code
istringstream iss ( line );
string thisname;
double gpa;
double new_gpa = 2.1;
if( iss >> thisname >> gpa)
{
if (thisname == name)
{
cout << name <<endl;
cout << gpa <<endl;
ofstream myfile;
myfile.open("alpha.dat",std::ios_base::app);
myfile << " \n" << name << " " << gpa+ new_gpa;
myfile.close();
read_file.close();
}
}
}
}
}
return 0;
}

You open file with std::ios_base::app, which means all you output operations are performed at the end of file, appending the content to the current file. But what you want to do is modify the data at the original place. So you should open file with std::ios_base::in, and function seekp can help you in the next step.

Related

replacing string based on user input c++

i want to receive an input from user and search a file for that input. when i found a line that includes that specific word, i want to print it and get another input to change a part of that line based on second user input with third user input. (I'm writing a hospital management app and this is a part of project that patients and edit their document).
i completed 90 percent of the project but i don't know how to replace it. check out following code:
#include <iostream>
#include <stream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in|ios::out);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
Myfile.close();
}
for example my file contains this line ( David , ha , 2002 ) and user wants to change 2002 to 2003
You cannot replace the string directly in the file. You have to:
Write to a temporary file what you read & changed.
Rename the original one (or delete it if you are sure everything went fine).
Rename the temporary file to the original one.
Ideally, the rename part should be done in one step. For instance, you do not want to end up with no file because the original file was deleted but the temporary one was not renamed due to some error - see your OS documentation for this.
Here's an idea:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
using namespace std;
void replace(string& s, const string& old_str, const string& new_str)
{
for (size_t off = 0, found_idx = s.find(old_str, off); found_idx != string::npos; off += new_str.length(), found_idx = s.find(old_str, off))
s.replace(found_idx, old_str.length(), new_str);
}
int main()
{
const char* in_fn = "c:/temp/in.txt";
const char* bak_fn = "c:/temp/in.bak";
const char* tmp_fn = "c:/temp/tmp.txt";
const char* out_fn = "c:/temp/out.txt";
string old_str{ "2002" };
string new_str{ "2003" };
// read, rename, write
{
ifstream in{ in_fn };
if (!in)
return -1; // could not open
ofstream tmp{ tmp_fn };
if (!tmp)
return -2; // could not open
string line;
while (getline(in, line))
{
replace(line, old_str, new_str);
tmp << line << endl;
}
} // in & tmp are closed here
// this should be done in one step
{
remove(bak_fn);
rename(in_fn, bak_fn);
remove(out_fn);
rename(tmp_fn, in_fn);
remove(tmp_fn);
}
return 0;
}
One possible way:
Close the file after you read it into "line" variable, then:
std::replace(0, line.length(), "2002", "2003")
Then overwrite the old file.
Note that std::replace is different from string::replace!!
The header is supposed to be <fstream> rather than <stream>
you can't read and write to a file simultaneously so I have closed the file after reading before reopening the file for writing.
instead of updating text inside the file, your line can be updated and then written to file.
#include <iostream>
#include <fstream>
#include <string.h>
#include <string>
using namespace std;
int main(){
string srch;
string line, line2;
fstream Myfile;
string word, replacement, name;
int counter;
Myfile.open("Patientlist.txt", ios::in);
cout << "\nEnter your Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open())
{
while(getline(Myfile, line)){
if (line.find(srch) != string::npos){
cout << "\nYour details are: \n" << line << endl << "What do you want to change? *type it's word and then type the replacement!*" << endl;
cin >> word >> replacement;
int index = line.find(word);
if (index != string::npos){
Myfile.close();
Myfile.open("Patientlist.txt", ios::out);
line.replace(index, word.length(), replacement);
Myfile.write(line.data(), line.size());
Myfile.close();
}
}
// i want to change in here
}
}else
{
cout << "\nSearch Failed... Patient not found!" << endl;
}
}

Naming an output file from a user entered string

This is my first project in C++. I took a course using C previously and file I/O seems to differ a little.
The project requires the user to enter a name for saving the output file.
I know I should use ofstream which should look like this:
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
I've bolded the snippet that's causing confusion.
How can I name the file from a string entered by the user?
*Note, C type string, so an array of characters.
#include < string > is not allowed
As my other answer has got a negative vote, here's another solution without #include <string>
You can just save the input from the user in a temporary char array and then save it to a string variable std::string.
Includes that are necessary:
#include <iostream>
#include <fstream>
Saving an input from an user into a char array:
char input[260];
cin >> input;
To then save it in a string variable just do this:
string filename = input;
To open a file stream you'll need to use std::ofstream. Please keep in mind, that the file is created in the same folder as the project/application is.
std::ofstream outfile (filename + "." + "file extension");
And as you already know this outfile.open(); opens the file.
With outfile << "hello"; you can write into the file.
To close the file, use outfile.close(); to close the file.
Here you have a little example code:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char input[260];
cin >> input;
string filename = input;
ofstream outfile(filename + "." + "txt");
outfile << "hello";
outfile.close();
}
I hope this helps.
Regards.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string path;
string name;
string h_path;
string text;
void create() {
ofstream file(h_path, ios::app);
if (!file.fail()) {
file << text;
file.close();
}
}
int main() {
cout << "please enter path(c:\\folder\): ";
cin >> path;
cin.ignore();
path = path + "/";
cout << "please enter the name of the file (test.txt): ";
getline(cin, name);
cout << "content of the file: ";
getline(cin, text);
h_path = path + name;
create();
cout << "new file created";
cout << h_path;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string fileName;
cin >> fileName;
ofstream myfile;
myfile.open(fileName);
myfile << "Writing this to a file.\n";
myfile.close();
}

Numbering Lines in a File With C++

I wrote a quick C++ program that asks the user for a input text file and an output text file. The program is then supposed to number the lines in the file on the left margin. However, I cannot seem to get it working properly, it compiles fine but does not number the lines like it is supposed to. I believe it is a logical error on my part. I am also not too familiar with file i/o in C++ as I am just learning it now using old school textbooks.
Here is the file:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
int main(void)
{int i = 0 , num = 1;
string inputFileName;
string outputFileName;
string s;
ifstream fileIn;
ofstream fileOut;
char ch;
cout<<"Enter name of input file: ";
cin>>inputFileName;
cout<<"Enter name of output file: ";
cin>>outputFileName;
fileIn.open(inputFileName.data());
fileOut.open(outputFileName.data());
assert(fileIn.is_open() );
assert(fileOut.is_open() );
while (!(fileIn.eof()))
{ch=fileIn.get();
if (ch=='\n') num++;
fileOut << num << "\n";
s.insert(i,1,ch); //insert character at position i
i++;
}
fileOut << s;
fileIn.close();
fileOut.close();
return 0;
}
If anyone could point me in thr right direction or give me some tips I would be eternally grateful.
int i = 0;
string line;
while (getline(infile, line))
{
outfile << (i++) << " " << line << "\n";
}

c++ file search database file and cout next line

I have 2 codes here, the first one here prompts you for a number, then tells you what is on that line number in the text file "example.txt"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string s;
vector <string> v;
ifstream fileInput;
int qwe = 0;
fileInput.open("example.txt");
while (getline( fileInput, s ))
{
v.push_back( s );
}
cout << "number: " << endl;
cin >> qwe;
cout << "line " << qwe << ": " << v[ qwe ] << endl;
fileInput.close();
}
and a second code here prompts the user for input then adds a "?" at the beginning because it's for my algorithm in the future, it will be used then. But then it searches for that in the text file and gives the user the line number of what the user inputted
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ifstream fileInput;
int offset;
string line;
string search;
cout << "Hi" << endl;
getline(cin, search);
search = "?" + search;
// open file to search
fileInput.open("example.txt");
if(fileInput.is_open())
{
while(getline(fileInput, line))
{
for(unsigned int curLine = 2; getline(fileInput, line); curLine++)
{
if (line.find(search) != string::npos)
{
cout << "found: " << search << " line: " << curLine << endl;
}
}
}
fileInput.close();
}
else cout << "Unable to open file.";
}
So my problem is that I need to sort of combine these codes, I need it so that it prompts the user for input and then it figures out the line number, and then it couts the next line, how do I do this?
Like this would do:
#include <fstream>
#include <algorithm>
#include <iostream>
int main()
{
std::string input;
std::cout<<"Enter a line to search for: \n";
std::getline(std::cin, input);
std::fstream File("example.txt", std::ios::in);
if (File.is_open())
{
std::string line;
int line_count = 0;
while(std::getline(File, line))
{
if (line.find(input) != std::string::npos)
{
std::cout<<"The line found was: \""<<line<<"\" at line: "<<line_count<<"\n";
if (std::getline(File, line))
{
std::cout<<"The line after that is: \""<<line<<"\"\n";
++line_count;
}
else
{
std::cout<<"There are no lines after that!\n";
}
}
++line_count;
}
File.close();
}
}
With an example file of:
hello world
I am testing
finding lines
you can search for "hello" and it will return line 0 aka the first line..
However, if you turn on find_approximate_line and searched for "hey world", it will still return line 0 because of the HammingDistance algorithm.
If you don't care about partial/close matches then you can remove the HammingDistance algorithm and keep using the std::string.find.
One example output is:
Enter a line to search for:
> hello world
The line found was: "hello world" at line: 0
The line after that is: "I am testing"

C++ Displaying a Text File...("Echo" a Text File)

So I'm really stuck trying to figured this bug on the program that is preventing me from displaying the text of my program..
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
using namespace std;
int main ()
{
ifstream infile;
ofstream offile;
char text[1024];
cout <<"Please enter the name of the file: \n";
cin >> text;
infile.open(text);
string scores; // this lines...
getline(infile, scores, '\0'); // is what I'm using...
cout << scores << endl; // to display the file...
string name1;
int name2;
string name3;
int name4;
infile >> name1;
infile >> name2;
infile >> name3;
infile >> name4;
cout << "these two individual with their age add are" << name2 + name4 <<endl;
// 23 + 27
//the result I get is a bunch of numbers...
return 0;
}
Is there any way cleaner or simple method i can used to display the file ?
All the method in the internet are difficult to understand or keep track due to
the file is open in loop..
I want a program that you type the name of the file and displays the file
the file will contain the following...
jack 23
smith 27
Also I need to obtain data from the file now I'm using the above code to obtain that information from the file...
loop is probably the best thing you can do.
so if you know the format you could simply do it like this
#include <iostream>
#include <fstream>
using namespace std;
int printParsedFile(string fileName) { // declaration of a function that reads from file passed as argument
fstream f; // file stream
f.open(fileName.c_str(), ios_base::in); // open file for reading
if (f.good()) { // check if the file can be read
string tmp; // temp variable we will use for getting chunked data
while(!f.eof()) { // read data until the end of file is reached
f >> tmp; // get first chunk of data
cout << tmp << "\t"; // and print it to the console
f >> tmp; // get another chunk
cout << tmp << endl; // and print it as well
} else {
return -1; // failed to open the file
}
return 0; // file opened and read successfully
}
you can call then this function for example in your main() function to read and display file passed as argument
int main(int argc, char** argv) {
string file;
cout << "enter name of the file to read from: "
cin >> file;
printParsedFile(file);
return 0;
}
I personally use stringstreams for reading one line at a time and parsing it:
For example:
#include <fstream>
#include <stringstream>
#include <string>
std::string filename;
// Get name of your file
std::cout << "Enter the name of your file ";
std::cin >> filename;
// Open it
std::ifstream infs( filename );
std::string line;
getline( infs, line );
while( infs.good() ) {
std::istringstream lineStream( line );
std::string name;
int age;
lineStream >> name >> age;
std::cout << "Name = " << name << " age = " << age << std::endl;
getline( infs, line );
}