[try Beta version]
Not logged in

 
classes infile problem!!

May 13, 2013 at 2:09am
I just learned classes for a short time. The problem I have commented 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
#include <iostream>
#include <fstream>
using namespace std;
class Circle{
    public:
        double radius;
        string color;
};
const int n=3;
Circle readin();

int main(){
    Circle circarr[n];
    for(int i=0;i<n;i++){
        cout<<i<<':'<<endl;
        circarr[i]=readin();
        cout<<circarr[i].radius<<" "<<circarr[i].color<<endl;
    }
    for(int i=0;i<n;i++){
        if(circarr[i].color=="yellow")
            cout<<i<<" is porn."<<endl;
    }
    return 0;
}

Circle readin(){
    Circle circ;
    ifstream infile("l16.txt");//Here the function only read the first, how to correct it?
    infile>>circ.radius>>circ.color;
    return circ;
}
May 13, 2013 at 5:32am
it's happen that everytime you call readin(), the function declares a new 'infile' variable (cause it's local), so it reads in the file, returns 'circ', closes file. the next time you call readin(), it starts from the beginning of the file again and again. If im not wrong you should declare infile in the main() function and pass it to the readin() funtion.

ps: sr for my bad English
Last edited on May 13, 2013 at 5:33am
Topic archived. No new replies allowed.