How to read this type of name in file i/o c++

Recently i have learnt how to read file and store data to the class in c++.
But there a harder exercise that i have no idea to do.

Here are the text file

Id name point
1 tran van an 5 6 7
2 tran bao 9 9 9
3 nguyen tran gia bao 8 9 4
4 bao 5 7 8

How to read name which length is random like this, i only know how to handle name variable with same length.
Last edited on
Hello Brjdyxter,

What have you do so far and can you post it, i.e., code.

Is the input file fixed or do you have the ability to change it?

Andy
A simple way to do this could be:

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

struct Record {
	int id;
	std::string name;
	int point[3];
};

std::istream& operator>>(std::istream& is, Record& r)
{
	is >> r.id;
	r.name.clear();

	std::string line;

	for (; (is >> line) && !isdigit(line[0]); r.name += line + ' ');

	if (is) {
		r.name.resize(r.name.size() - 1);
		r.point[0] = std::stoi(line);
		is >> r.point[1] >> r.point[2];
	}

	return is;
}

int main()
{
	std::ifstream ifs("harder.txt");

	if (!ifs.is_open())
		return (std::cout << "Cannot open file\n"), 1;

	std::string line;
	std::vector<Record> recs;

	std::getline(ifs, line);	//Skip over header

	for (Record r; ifs >> r; recs.push_back(r));

	for (const auto& r : recs)
		std::cout << r.name << '\n';
}


Given the sample input file in the first post, displays:


tran van an
tran bao
nguyen tran gia bao
bao

Last edited on
Topic archived. No new replies allowed.