How to separate individual items in a string from a file of data?

Basically, i want to separate a string from a file and then input it into a new txt file.
For instance, in the file i will have...

Jessica McKay 45 67 78
Daniel Lun 22 44 54
Mike John Joseph 35 67 45 23

Then to sort the data in this format:

Name: Jessica McKay
Age: 45
Scores: 67 78

so far i have this:

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

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

int main()
{
	ifstream myfile("scores.txt");
	string mystring;

	cout << "The file contains the following scores: " << endl;

		while (!myfile.eof())
		{
			myfile >> mystring;
			cout << mystring << endl;
		}
	
	myfile.close();
			
	char name [20];
	int student_id;
	char group;
	string marks[4];
	int avg;
	char status [10];
...


I dont know how i should intend to do it, but i think i need to do something like:

take the 1st line and then seperate the words and numbers by reading each word/number seperated by a whitespace?

May i kindly ask for help, ive been doing this the whole day and dont know how to do it :(
Based upon the sample input data, the person may have a variable number of names, an age, and then a variable number of scores.
Jessica McKay 45 67 78
Daniel Lun 22 44 54
Mike John Joseph 35 67 45 23

Thus it seems that each individual line must be broken into words.
If the word is alphabetic, it is part of the name. If its numeric, it must be
the age. After that, any further numeric values must be scores.

I'd suggest using getline() to read each line into a standard C++ string.
Then use a stringstream initialised from that line of text.
The stringstream can be used in the same way as other input streams, to get a word at a time.

I'd put the high-level structure in main() and then call a separate function to handle each line.
Last edited on
Topic archived. No new replies allowed.