ifstream and getline

closed account (DEUX92yv)
The "name" field is a first and last name. I'd like to not have to concatenate strings to get them into one variable. How do you use ifstream and getline to do this? I have a syntax error. My problem is that I don't know how long the name will be, and I don't want to decide a limit. I thought that getline() could work with one argument, but obviously this isn't the way to go about it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int read_friends(char *infile)
// Reads users from given file
{
	int initusers, id, year, zip;
	string name;
	ifstream readfriends;
	readfriends.open(infile);
	if (! readfriends.is_open()) {
		cout << "Failed to open " << infile << endl;
		return -1;
	}
	readfriends >> initusers;
	while (readfriends.good()) {
		readfriends >> id;
		readfriends.getline() >> name; // This is where I don't know the syntax
		readfriends >> year;
		readfriends >> zip;
		add_user(name, year, zip);
	}
	readfriends.close();
	return 0;
}


EDIT: getline(readfriends, name); seems to do the trick.
Last edited on
replace

readfriends.getline() >> name;

with

getline( readfriends, name )

For more information:
http://www.cplusplus.com/reference/string/getline/


and if you want to use istream :: getline( ) , it's prototype is

getline (char* s, streamsize n, char delim );

by default delim is '\n'
But here the first parameter is not string&, it is char*
Last edited on
Topic archived. No new replies allowed.