Reading from a file

Can I have help writing the read function for my code? Not sure what to do, and I know what I have now just isn't working.


I want to start over with some help. Any ideas??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  void readData(void)
{
	ofstream test;
	test.open("c:/TestAddress.txt");
	ifstream inMyStream(FileName, ios::in);
	string firstline;
	inMyStream >> firstline;
	int i = 0;
		getline(inMyStream, firstline, '\n');
		cout << endl;
		string *theFields = split(firstline, ',');
		cout << "Name...... " << theFields[i];
		i++;
		cout << "\nStreet.... " << theFields[i];
		i++;
		cout << "\nCity...... " << theFields[i];
		i++; 
		cout << "\nState..... " << theFields[i];
		i++; 
		cout << "\nZip code.. " << theFields[i] << endl;
		i++;
	test.close();
}//end read data 


The whole code:
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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
string * split(string, char);

const char FileName[] = "TestAddress.txt";
int main()
{
	menu();
	return 0;
} //end main

void menu(void)
{
	char answer;
	int i = 0, x = 0;
	while (i == 0)
	{
		cout << "What would you like to do?\n";
		cout << "Append Records (A), Display Records (D), or Quit (Q)\n";
		cin >> answer;
		answer = tolower(answer);
		switch (answer)
		{
		case 'a': writeData(); break;
		case 'd': readData(); break;
		case 'q': return;
		default: x = 1; break;
		} //end switch

		while (x != 0)
		{
			cout << "\n\nError: Append Records (A), Display Records (D), or Quit (Q):\t";
			cin >> answer;
			cout << "\n\n" << endl;
			if ((answer == 'a') || (answer == 'd') || (answer == 'q'))
			{
				x = 1;
				break;
			}//end if
			else
			{
				break;
			}//end else
		}//end second while
	}//end first while
	cout << "\nWhat would you like to do now?\n";
	cout << "Append Records (A), Display Records (D), or Quit (Q)\n";
	cin >> answer;
}//end menu

void writeData(void)
{
	char answer;
	string name = " ";
	string street = " ";
	string city = " ";
	string state = " ";
	string zipCode = " ";
	ofstream test("c:\\desktop\\TestAddress.txt", ios::app);

	do
	{
		cin.ignore(); //need this or else it will skip name inpout
		cout << "\nName: ";
		getline(cin, name);
		cout << "\nStreet: ";
		getline(cin, street);
		cout << "\nCity: ";
		getline(cin, city);
		cout << "\nState: ";
		getline(cin, state);
		cout << "\nZip code: ";
		getline(cin, zipCode);

		test << name << "," << street << "," << city << "," << state << "," << zipCode;

		cout << "\nEnter another Record? (Y/N) ";
		cin >> answer;
		answer = tolower(answer);
	} while (answer == 'y');
	test.close();
	return;
}//end write data

void readData(void)
{
	ofstream test;
	test.open("c:/TestAddress.txt");
	ifstream inMyStream(FileName, ios::in);
	string firstline;
	inMyStream >> firstline;
	int i = 0;
		getline(inMyStream, firstline, '\n');
		cout << endl;
		string *theFields = split(firstline, ',');
		cout << "Name...... " << theFields[i];
		i++;
		cout << "\nStreet.... " << theFields[i];
		i++;
		cout << "\nCity...... " << theFields[i];
		i++; 
		cout << "\nState..... " << theFields[i];
		i++; 
		cout << "\nZip code.. " << theFields[i] << endl;
		i++;
	test.close();
}//end read data

string * split(string theLine, char theDeliminator){

	int splitCount = 0;
	for (int i = 0; i < theLine.size(); i++){
		if (theLine[i] == theDeliminator)
			splitCount++;
	}
	splitCount++; 
	string* theFieldArray;
	theFieldArray = new string[splitCount];
	//split the string into seperate fields
	string theField = "";
	int commaCount = 0;

	int i = 0;

	for (int i = 0; i < theLine.size(); i++){ //read each character and look for the deliminator
		if (theLine[i] != theDeliminator) {
			theField += theLine[i]; //build the field
		}
		else { //the deliminator was hit so save to the field to the array
			theFieldArray[commaCount] = theField; //save the field to the array
			theField = ",";
			commaCount++;
		}
	}
	theFieldArray[commaCount] = theField; //the last field is not marked with a comma...

	return theFieldArray;
} //end split
If you are allowed, structures & vector will make your life easier

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
#include <iostream>
#include <fstream>
#include <string>
#include <vector> // vector<>
#include <limits> // numeric_limits<>

using namespace std;

// http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/
struct Record {
    string name;
    string street;
    string state;
    int zip_code;
};

/* Format of the file :
 * name
 * street
 * state
 * zip_code
 * ...
 */

// http://www.learncpp.com/cpp-programming/16-2-stl-containers-overview/
vector<Record> readData( const char* filename )
{
    ifstream test( filename );

    vector<Record> records;
    Record temp;

    while( getline(test, temp.name) &&
           getline(test, temp.street) &&
           getline(test, temp.state ) &&
           test >> temp.zip_code &&
           test.ignore(numeric_limits<streamsize>::max(), '\n') ) // discards newline after zip_code
                                                                // otherwise, getline() will eat this
                                                                // and the program would not work
                                                                // correctly
    {
        records.push_back(temp); // add temp to vector
    }

    return records;
}

// http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
void appendData( ofstream& os, const Record& record )
{
    os << record.name   << '\n'
       << record.street << '\n'
       << record.state  << '\n'
       << record.zip_code << '\n'
       << flush; // make sure all these text are written
}

int main()
{
    const char FileName[] = "TestAddress.txt";
    bool running = true;

    while( running )
    {
        cout << "What would you like to do?\n";
        cout << "Append Records (A), Display Records (D), or Quit (Q)\n";
        char answer;
        cin >> answer;

        switch( tolower(answer) )
        {
        case 'a' :
            {
                ofstream os( FileName );

                Record temp;
                
                // prompt info

                appendData( os, temp );
            }
            break;
        case 'd' :
            {
                vector<Record> records = readData( FileName ); // or auto records = .. in C++11
                
                // http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html
                // for( size_t i = 0; i < records.size(); ++i ) // if ur compiler doesn't support C++11
                for( const auto& i : records ) 
                {
                   // records[i].name if u use the first form of for()

                    cout << i.name << " " << i.street << " " << i.state << " " << i.zip_code << '\n'
                         << endl;
                }
            }
            break;
        case 'q' :
            running = false;
            break;
        default :
            cout << "Invalid answer\n";
        }
    }
}
Last edited on
Well, I don't think I'm allowed to use those, it would defeat the purpose of the code she asked us to use, but I'd be interested into looking into these later, especially considering that this is the last lab I'm supposed to do and I still haven't heard of them.

Thanks for your input, I suppose I'll just have to try harder!
Last edited on
Topic archived. No new replies allowed.