Storing information in a simple c++ program

Jan 18, 2008 at 1:22pm
Alright, so i'm currently making a simple console program which I need to be able to store information from each time I run it. As far as I can understand - the best and easiest way to do this is to have the program store the information in a .txt file.

Now, a few things:
1. I want to be able to store both numbers, aswell as characters (in the form of names) in the same text document. Later on I wish to recall these values and use them in my program, either in multiplications or in lines of text.
Now as far as I can understand, it's not possible to, in any way "Declare" a given location to a value when storing it in a text document in such a way that it's easy to get ahold of later, am I correct?

This is an example of what I'd like my program to do;
"Input your name:" I'll input John Travolta
"Input your age:" I'll input 40
it then stores this information in a text document, then later I can start the program again and per say, I can run a command to find out what half of my age is, the program then finds my age, stored in the text document, divides it by two and returns that.

Is this possible?
I can easily make a program that stores this information in a text file, like this;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
  string tango;
  ofstream myfile;
  myfile.open ("example.txt");
  for (int a = 0; a<20; a++)
  {
	  cout << "What do you want to write in your .txt file?";
	  cin >> tango;
  myfile << tango << endl;
}
  myfile.close();
return 0;
}


And I can write 20 things on here. I can also find all these information and store each line in a string, now if I organize my program carefully it'd still be possible for me to organize such that "Name" is always stored in string[2], I could in other words create a program like this;

1
2
3
4
5
6
7
8
9
10
    string info[20];
    int a = 1;
    while (! myfile.eof() )
    {
      getline (myfile,line);
      info[a] = line;
      a++;
    }
    myfile.close();
  }


All the information would be stored in the string a,and knowing that the third question my program asked was per say the persons age, I could pick this up later in my program by running the function that prints everything to a string called info and returns it to where I am in the program, and then do:

1
2
int b = info[3]/2;
cout << "half your age is: " << b;


This brings with it a few other problems of course - is there any way I can store both names, and numbers in the same type of file? So that I can simply run a function and get all my info returned like I want to?
And another thing - let's say the person using this program just had his birthday, he'd like to go in and change his age - but only his age, he doesn't want to rewrite all his information again, is there any way I can browse my way to this specific tidbit of information in my .txt document and change only that?

Hope this didn't get too long, thanks in advance to any help given.
Jan 18, 2008 at 11:01pm
I am only a beginner at c++ , but go to the 'article' forums and siavoshkc has made a thread 'You want to build a program but where to start?' and that does almost exactly what you want. a link to it is:
[url]http://www.cplusplus.com/forum/articles/11/[/url]
His program stores students names and marks in a text document and accesses them when you start the program later.
Last edited on Jan 18, 2008 at 11:15pm
Jan 19, 2008 at 12:16am
Your problem, as I see it, is that the integer 'age' is going to be stored in your text file in char format. So you're going to have to do some conversion work to get your numeric information back in a useable format.

I've thrown together the following piece of VERY rudimentary code (with lots of comments) to give an idea of what you need to do. It should compile and run. Being a bit simpler than siavoshkc's program mentioned by tomao it might help a little more to get the idea of what you have to do.

BUT I do warn you that it's not a very elegant solution - it's just an aid to understanding. Most of it's faults should be pretty apparent :) but the really important bit, I think, is the char to int conversion near the end. The rest I think you already know how to do.

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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// integer_file_io.cpp -- save to a file and read back
// the following is a VERY rudimentary piece of code serving ONLY
// to demonstrate a principle in reading string and numeric data from
// a text file. A fully functional program would do it VERY differently
#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
    // declare two variables;
    char name[20];
    int age;
    
    // get user to input these;
    cout << "\n\nWhat is your name: ";
    cin >> name;
    cout << "What is your age : ";
    cin >> age;
    
    // create output stream object for new file and call it fout
    // use this to output data to the file "test.txt"
    char filename[] = "test.txt";
    ofstream fout(filename);
    fout << name << "," << age << "\n";	   // name, age to file
    fout.close();	// close file
    
    // output name and age : as originally entered
    cout << "\n\n--------------------------------------------------------"
         << "\n name and age data as entered"
         << "\n--------------------------------------------------------";
    cout << "\n\n    Your name is: " << name;
    cout << "\n    and your age is: " << age;     

    // output name and age : as taken from file           

    // first display the header
    cout << "\n\n--------------------------------------------------------"
         << "\n name and age data from file"
         << "\n--------------------------------------------------------";   

    // and now the tricky stuff;

    // open the file for reading
    // create input stream object for new file and call it fin
    ifstream fin(filename);
    
    // get one line of data from the file
    char line[50];               // temporarily contains file input
    fin.getline(line, 50);       // put the line in line[]

    /* Now we're going to "split" the data - reading through the data contained
       in line[] using an index variable, transferring the name (everything
       occuring before the comma) to one array, and the age (everything after
       the comma) to another. */

    // read in the name string
    /* NOTE: we need to terminate fname[] with a null string as it originally
       contained nothing but random stuff. Fortunately, the final act of the
       do-while loop will be to increment count _after_ we have copied the last 
       piece of data from line[] to fname[]. Thus we can close off this section
       by simply placing a null string in fname[count]. */
       
    char fname[20];      // array to hold the name
    int count = 0;       // count variable for do - while loop
    do
    {
        fname[count] = line[count];    // copy elements across arrays   
        count++;
    }
    while (line[count] != ',');        // check for separator - keep going until ','
    fname[count] = '\0';               // terminate fname[] with null char
    
    // read in the age
    /* We will continue to use count to work through line[], but one piece of
       housekeeping first; when we left the above do-while loop the value of
       count was such that line[count] is the element containing the comma.
       so we first increment count such that line[count] is the start of the
       age */
    count++;
    char fage_ch[10];    // array to hold the age in char format
    /* While we can continue to move through line[] using count as an index this
       will not do for age - we want to start at fage_ch[0] NOT fage_ch[count] -
       so we initialize a seperate index variable for fage_ch[]
    */
    int fage_count = 0;   
    do
    {
        fage_ch[fage_count] = line[count];   // copy elements across arrays
        fage_count++; count++;               // increment BOTH count variables
    }
    while (line[count] != '\0');             // check for end of line
    fage_ch[fage_count] = '\0';
    
    // now need to convert the char format age in fage_ch[] to an integer
    /* this is pretty easy, as it turns out...
       What we want to do is convert the elements of fage_ch[] to integers
       weight them (i.e. muliply by 10, 100, 1000 etc) and add them to convert
       a string such as '1234' into an integer; (1000x1) + (100x2) + (10x3) + 1.
       This is very simple if we can determine which is the last character in
       the array. And, fortunately, we left the last do-while loop with
       fage_count set such that fage_ch[fage_count] IS the final element of the 
       array (the null character).
       Thus, all we need to do is use a running total and;
           Set the running total to zero,
           Convert the first element of fage_ch[] to int using atoi(),
           Add it to the running total,
           Check if we are at the end of the array (using fage_count)
       If we have more elements to process;
           Multiply the total by ten,
           Convert the next element of fage_ch[] to int,
           Add it to the running total,
           Check for end of array.
       And we keep going until we have reached the end of the array.
       Here's the code;
    */            
    int fage_int = 0;        // this will hold the integer value of age
    int total = 0;           // holds a running total
    char temp;               // holds the char being converted
    
    for (int i = 0; i < (fage_count); i++)
    {
        temp = fage_ch[i];
        total = 10*total + atoi(&temp);
    }

    fage_int = total;

    /* Now, because fage_int is an integer (and not an array of char like
       fage_ch[], you can actually do things like multiply, divide, etc. So
       after all the hard work above, you finally have data you can use
    */

    // display data
    cout << "\n\n    Your name is: " << fname;
    cout << "\n    and your age is: " << fage_int;
    cout << "\n\n--------------------------------------------------------";    
    
    // display exit message
    cout << "\n\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}


Hope it helps,
Muzhogg
Last edited on Jan 19, 2008 at 12:49am
Jan 19, 2008 at 12:55am
Oh, and I should have mentioned...

Once you get your data OUT of the file, it's pretty easy to modify it and stuff it back in.

All you would have to do is modify your data and then;

fout << fname << "," << fage_int << "\n"; // write updated data to file

Muzhogg
Topic archived. No new replies allowed.