input from file

I am having difficulty getting input from a file because I can't figure out how to create a function inside a class that will transfer the data to the class variables. I cannot find an example to work from anywhere. Is there a standard formula for this?
This code is working to read the file, but I don't need a string out, I need to input the data to a char, and six doubles.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () 
{
ifstream infile("Stocks.txt");
        
        string line;
if( infile.is_open() )
{
while( getline(infile,line) )
{
cout << line << endl;

}
}

system("pause");
  return 0;
}
input the data to a char, and six doubles

Reading from a file is very similar to reading from cin. Instead of
 
    cin >> x >> y >> z
it becomes
 
    infile >> x >> y >> z


Is there a standard formula for this?

It will depend on the format of the file - sometimes there are commas, or names which contain spaces etc, it depends on the data. One thing that might be considered common, if not 'standard', is to place the input statements inside the condition of a while loop
1
2
3
4
while (infile >> x >> y >> z)
{
    // do something with x, y and z
}

The standard formula reading values into a class is by overloading the '>>' operator.
Similar is the writing to an ofstream by overloading the '<<'.

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
#include <string>
#include <fstream>
#include <iostream>
using namespace std;

class Person {
    int m_age;
    string m_name;
public:
    int age() const { return m_age; }
    void set_age( int age) { m_age = age; }
    string name() const { return m_name; }
    void set_name(const string& name) { m_name = name; }
};

// Reading into the class by overloading the >> operator.

istream& operator>>( istream& istr, Person& person)
{
    string name;
    int age;

    istr >> name >> age;

    person.set_name( name );
    person.set_age( age );
    
    return istr;
}


// Similar, the writing from class to a ostream:

ostream& operator<<( ostream& ostr, const Person& person)
{
    ostr << person.name() << ' ' << person.age() << endl;

    return ostr;
}

// And so the whole will work:

int main()
{
    Person person;
    cin >> person;

    ofstream ofstr {"exampleFile.txt"};
    ofstr << person;
    ofstr.close();

    Person other_person;
    ifstream ifstr {"exampleFile.txt" };
    ifstr >>  other_person;
    cout << other_person;
}

*edited
Last edited on
Wow, no I mean wow! Thank you both so much! Now it makes sense to me. I just needed a little explanation and a great example, and that is exactly what I got you guys a re the best.
Topic archived. No new replies allowed.