Hi, I was wondering if there was a way to get a variable from a text file, input data to change it, and save it to be used later, all in C++. Thanks in advance.
#include <fstream> //for ifstream and ofstream
#include <iostream>
#include <string> //for the string class
#include <sstream> //for stringstream
usingnamespace std;
template <typename T>
void GetAVariableFromATextFile(constchar* textFileLocation, T& variableFromATextFile)
{
//open the text file
ifstream textFile(textFileLocation);
if( textFile.is_open() )
{
//get the variable (assumed to be on the first line of the text file)
string variableFromATextFileAsString;
getline( textFile, variableFromATextFileAsString );
textFile.close();
//convert the variable from a string into T
//using a stringstream (handy)
stringstream ss( variableFromATextFileAsString );
ss >> variableFromATextFile;
}
}
template <typename T>
void ChangeIt(T& it, T data) //passing it by reference because it's going to change
{
//use the data to change it
it = data;
}
template <typename T>
void SaveItToBeUsedLater(constchar* textFileLocation, T it)
{
//create a text file (or overwrite the one we used before)
ofstream textFile(textFileLocation);
//save it to be used later (put the value on the first line)
textFile << it;
textFile.close();
}
int main()
{
constchar* fileLocation = "C:\\jjw1993\\files\\file.txt";
double doubleFromTextFile = 0; //any other plain old data will work
//Get a variable from a text file
GetAVariableFromATextFile( fileLocation, doubleFromTextFile );
cout << "A variable from a text file: " << doubleFromTextFile << endl;
//Input data to change it
double data = 0;
cout << "Input data to change it: ";
cin >> data;
cin.sync();
//now change it
ChangeIt( doubleFromTextFile, data );
//Ask the user if they want to save it to be used later
char saveItToBeUsedLaterYOrN = 'n';
cout << "Save it to be used later? (y/n): ";
cin >> saveItToBeUsedLaterYOrN;
cin.sync();
if( (saveItToBeUsedLaterYOrN == 'y') || (saveItToBeUsedLaterYOrN == 'Y') )
{
//Save it to be used later
SaveItToBeUsedLater( fileLocation, doubleFromTextFile );
cout << "Saved it to be used later!" << endl;
}
return 0;
}