How do I read in records using ifstream and string class?

I need to read data from a file one line at a time using ifstream and string class data type.

How do I do this?

Thank you!
closed account (j3Rz8vqX)
Something like the below...
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
#include <iostream>
#include <fstream>
using namespace std;

void PrintGreetingScreen()
{
    cout<<"This is the greeting screen.\nPress enter to continue: ";
    cin.ignore();
}
void OpenInputFile(fstream &infile)
{
    infile.open("addressList.txt", ios::in);
}
void OpenOutputFile(fstream &outfile)
{
    outfile.open("lab3output.txt", ios::out|ios::app);
}
void ReadInRecords(fstream &infile,string str[],int &size)
{
    if(infile.is_open())
    {
        string temp;
        while(!infile.eof() &&size<50)
        {
            // one record into a single string in this order:
                // last name, first name, street address, city, state, zip code. Hint: every 6 strings
                // do not put $ back into the record.
            for(int i=0;i<6;++i)
            {
                getline(infile,temp,'$');
                str[size].append(temp,0,20);
            }
            ++size;//Successfully acquired one record!
        }
        infile.close();
    }
}
void DisplayRecordsOnScreen(string str[],int size)
{
    for(int i=0;i<size;++i)
    {
        //Print something to the display...
    }
}
void WriteToOutputFile(fstream &outfile,string str[],int size)
{
    if(outfile.is_open())
    {
        for(int i=0;i<size;++i)
        {
            //Write something to the file...
        }
        outfile.close();
    }
}
int main()
{
    //The necessary data(s):
    fstream in,out;
    string data[50];
    int size=0;

    //The print function:
    PrintGreetingScreen();

    //File preparation functions:
    OpenInputFile(in);
    OpenOutputFile(out);

    //Input/Display/Output functions:
    ReadInRecords(in,data,size);
    DisplayRecordsOnScreen(data,size);
    WriteToOutputFile(out,data,size);

    /*
    AddNewRecords
    PrintCosingScreen
    */
    return 0;
}

I have provided an example of the ReadInRecords; not tested.

getline: http://www.cplusplus.com/reference/string/string/getline/
append: http://www.cplusplus.com/reference/string/string/append/
Last edited on
Thank you so much!!
Topic archived. No new replies allowed.