read file and put it into array

hello everyone! i want to ask how can I sort whose data with ' ' and "\n" .Then put them into array[1-5] for further implement.
let me explain more, like array[1] stores [name1,name2,name3] array[4] stores [height1,height3].

Thank you very much for your help.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
#include <algorithm>

using namespace std;

int main()
{
	ifstream myfile ("newfile.txt");
	if ( !myfile.is_open())
	{
		cout << "Fail" << endl;
	}
	else
		cout << "success" <<endl;
	
	/** The code enters here**/
return 0;
}


newfile.txt detail as below:
name1 age1 sex1 height1 weight1
name2 age2 sex2
name3 age3 sex3 height3
Last edited on
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
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>


int main()
{
    std::ifstream myfile("newfile.txt");
    if (!myfile.is_open())
        std::cout << "Fail"    << std::endl;
    else
        std::cout << "success" << std::endl;

    std::vector<std::string> array[5];
    std::string temp;
    //For each line in file
    while(std::getline(myfile, temp)) { 
        std::istringstream inp(temp);
        int i = 0;
        //We try to get as many values as possible
        //and store them in respective vector
        while(inp >> temp && i < 5)
            array[i++].push_back(temp);
    }
    //Output
    for(const auto& vec: array) {
        for(const auto& str: vec)
            std::cout << str << ' ';
        std::cout << '\n';
    }
}
success
name1 name2 name3
age1 age2 age3
sex1 sex2 sex3
height1 height3
weight1

Last edited on
Topic archived. No new replies allowed.