@kytcenochka

Чтение файла в массив. с++. Ошибки? Как считать файл в массив?

Помогите, пожалуйста, зависла на этом задании!

Файл содержит:
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;
}


Хочу получить
name [John, Ann, Erik]
age [20,29,7]
favourite_colour [yellow, green, red]
  • Вопрос задан
  • 183 просмотра
Пригласить эксперта
Ответы на вопрос 1
Punk_Joker
@Punk_Joker
Software Engineer в ВО Овен
Вместо string name[]; или использовать динамическое создание массива, либо std::vector. Ну ли в простом случае статически задать размер массива string name[3];
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы