program not working

What am I doing wrong, there is no output.

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
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
    
    ifstream file;
    string a[10];
    string z,pop1950,pop1970,pop1990,pop2010,pop2015,name;
    file.open("population.csv");
    if (!file.is_open()){
        cout <<"Error opening file" << endl;
        return 0;}
    if (file.is_open())
    {
        while (getline(file, z)) {
            z= pop1950 + " " + pop1970 + " " +pop1990+ " " + pop2010+ " " + pop2015;
            file>>z;
            getline(file, name);
            cout<<pop1950<<" "<<pop2015<<" "<<name<<endl;
        }
        
        file.close();
    }
    return 0;
}
Last edited on
Line 14: This if is not needed. If the file didn't open, line 13 provides an unconditional exit. You can only get to line 14 is the file is open.

Line 17: pop1950,pop1970,pop1990,pop2010,pop2015 are all empty strings. You haven't put anything in them. You're also overwriting the string you just read (z).

Since the extension of the file is .csv, I'm assuming the fields are separated by commas.
The typical idiom to parse a csv file is to use stringstream.

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

int main() 
{   ifstream file;
    string a[10];   //  What's this for?
    string z,pop1950,pop1970,pop1990,pop2010,pop2015,name;
    file.open("population.csv");
    if (!file.is_open())
    {   cout <<"Error opening file" << endl;
        return 1;
    }
    while (getline(file, z)) 
    {   stringstream ss (z);
        
        getline (ss, pop1950, ',');
        getline (ss, pop1970, ',');
        getline (ss, pop1990, ',');
        getline (ss, pop2010, ',');
        getline (ss, pop2015, '\n');
        //   getline(file, name);   //  Commented this out as not sure the format of your file
        cout << pop1950 << " " << pop2015 << endl;
    }
    return 0;
}


I did not test this since you did not provide a sample file.



Topic archived. No new replies allowed.