K
K
kytcenochka2018-04-05 12:58:51
C++ / C#
kytcenochka, 2018-04-05 12:58:51

Reading a file into an array. c++. Mistakes? How to read a file into an array?

Please help, I'm stuck on this task!
File contains:
John,20,yellow
An,29,green
Erik,7,red

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

struct personal_details
{
    string name[];
    int age[];
    string favourite_colour[];
};
int main()

{
    personal_details pd;
    ifstream infile;
    int i = 0; // counter to use determine the size of the array input
    infile.open("text.txt");
    if (!infile) {
        cout << "Unable to open file";
        exit(1); // terminate with error
    }
    while (infile) {
        getline(infile, pd.name[i], ',');
        infile >> pd.age[i];
        getline(infile, pd.favourite_colour[i], ',');
        i++;
    }
    infile.close();
    //display contents of each array
   for(int j = 0; j < i; j++) {
        cout << pd.name[j] << " ";
    }
    cout << endl;
    for(int j = 0; j < i; j++) {
        cout << pd.age[j] << " ";
    }
    cout << endl;
    for(int j = 0; j < i; j++) {
        cout << pd.favourite_colour[j] <<  " ";
    }
    return 0;
}

I want to get
name [John, Ann, Erik]
age [20,29,7]
favorite_colour [yellow, green, red]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sakhno, 2018-04-05
@Punk_Joker

Instead of string name[]; or use dynamic array creation, or std::vector. Whether well in a simple case statically to set the size of an array string name[3];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question