File Commands

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.
Yes there is. Don't forget to mark the thread as solved :)

EDIT: Please excuse my sarcasm. Here's some code to chew on.

(file.txt)
12345.678

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <fstream> //for ifstream and ofstream
#include <iostream>
#include <string> //for the string class
#include <sstream> //for stringstream
using namespace std; 

template <typename T>
void GetAVariableFromATextFile(const char* 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(const char* 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()
{
	const char* 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;
}
Last edited on
Topic archived. No new replies allowed.