reading from csv file

Hi forum I need help with reading from csv file.I have csv with content like this
1
2
3
1;Peter;230
5;Merrick;255
6;Lucky;430

So and I need save this strings to array like array[0]=1,array[1]=Peter,array[2]=230

But my while save String only on first index and I dont know how repaire it.
I will be glad for any help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  string array[100];
    fstream file;
    file.open("persons.csv",ios::in);
   while(!file.fail())
   {
      if(file==";")
      {
         i++; 
      }
      }


    getline(file,array[i]);

   }
   file.close();
It looks like you really need to review your documentation on how to do basic file input and output. Perhaps start here:
http://www.cplusplus.com/doc/tutorial/files/

Next, after you review your documentation you should realize that your variable file will never be equal to ";".
I'm not sure that a single array of strings is the best choice. You might use a 2D array, but maybe a vector of 'person' objects might be better.

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
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

struct Person {
    int id;
    std::string name;
    int num;
};

using namespace std;

int main()
{
    ifstream fin("persons.csv");
    if (!fin)
    {
        cout << "File not open\n";
        return 1;
    }
    
    vector<Person> persons;
    
    string line;
    const char delim = ';';
    
    while (getline(fin, line))
    {
        istringstream ss(line);
        Person person;
        ss >> person.id; ss.ignore(10, delim); 
        getline(ss, person.name,delim);
        ss >> person.num;
        if (ss)
            persons.push_back(person);
    }
    
    
    for (unsigned int i=0; i< persons.size(); i++)
        cout << setw(5)  << persons[i].id 
             << setw(25) << persons[i].name
             << setw(8)  << persons[i].num 
             << '\n';
}

Output
    1                    Peter     230
    5                  Merrick     255
    6                    Lucky     430

Topic archived. No new replies allowed.