need help in fstream, read input from txt

my txt file

number name email
123 david john email@email
456 oscar tan sin yi email@email
789 mohammad ali bin abu email@email


code
1
2
3
4
5
while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }


it store each line in "line" variable right?
if i need is something like this


"123" store in "number" variable
"david john", or "mohammad ali bin abu" store in "name" variable
"email@email" stored in "email" variable


does there anyway to do that? if yes, how can i do that? i just start learned fstream... still blur about it.... need help please
If you're familiar with how to use cin, you can use myfile in exactly the same way to accomplish what you want.
what i need is read input from txt file than store each information to different variable... the most tricky one is the name, because it has many spaces...
example

input >> number >> name >> email
//for this one (123 david john email@email)
123 will store in "number", david store in "name" and email store john


and what i want is
"123" store in "number"
"david john" store in "name"
"email@email" store in "email"


how can i do that?
Last edited on
use a suitable delimiter while writing to file
123:david john:email
use strtok function after reading line, to fetch them based on delimiter.
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
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <vector>
#include <iostream>
#include <fstream>
#include <string>

struct info
{
	std::string id ;
	std::string name ;
	std::string email ;
};

bool isEmail(const std::string& str)
{
	return std::string::npos != str.find('@') ;
}

std::istream& operator >>(std::istream& is, info & i )
{
	is >> i.id ;

	// remove previous name, if there was one.
	i.name.clear() ;

	// keep adding to name if current token isn't an email address.
	std::string input ;
	while ( is >> input && !isEmail(input) )
	{
		if (i.name.length())
			i.name += ' ' ;
		i.name += input ;
	}

	i.email = input;
	return is ;
}

std::ostream & operator <<(std::ostream& os, const info&i )
{
	return
		os << "ID: " << i.id 
		   << "\nName: " << i.name 
		   << "\nemail: " << i.email << "\n\n" ;
}


int main()
{
	std::ifstream myfile("test.txt") ;

	std::vector<info> contacts ;

	info contactInfo ;

	while ( myfile >> contactInfo )
		contacts.push_back(contactInfo) ;

	for ( auto i = contacts.begin(); i != contacts.end() ;  ++i )
		std::cout << *i ;
}
Topic archived. No new replies allowed.