I am trying to find and replace a line of data in a text file in c++. But I honestly have no idea where to start.
I was thinking of using replaceNumber.open(\"
You can use std::stringstream
to convert the string read from the file to an integer and use std::ofstream
with std::ofstream::trunc
to overwrite the file.
#include
#include
#include
#include
#include
#include
int main()
{
std::ifstream ifs("test.txt");
std::string line;
int num, other_num;
if(std::getline(ifs,line))
{
std::stringstream ss;
ss << line;
ss >> num;
}
else
{
std::cerr << "Error reading line from file" << std::endl;
return 1;
}
std::cout << "Enter a number to subtract from " << num << std::endl;
std::cin >> other_num;
int diff = num-other_num;
ifs.close();
//std::ofstream::trunc tells the OS to overwrite the file
std::ofstream ofs("test.txt",std::ofstream::trunc);
ofs << diff << std::endl;
ofs.close();
return 0;
}