I want to read the name (Last, First)

I want to read the name (Last, First)
for example I loaded Smith, Henry
but I use this code is showed"Smith, Henry"
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <fstream>
ifstream fin
	string	f_name;
	cout << "Enter input file name: ";
	getline(cin, f_name);
	fin.open(f_name.c_str());
	getline(fin, Last_Name,',');
	getline(fin, First_Name);
fin.close();		
cout << Last_Name + ", " + First_Name;

Why read the Last_Name correctly, but First_Name has a " Henry" extra space in here?
First, you're missing your using std namespace; declaration, that's a bad habit to form and it actually makes your code slightly harder to read.

To answer your question though, it's because "std::getline()" doesn't skip whitespace: http://www.cplusplus.com/reference/string/string/getline/ . Call the "find()" and "erase()" member functions for 'std::string' if you want to get rid of it.

- find(): http://www.cplusplus.com/reference/string/basic_string/find/
- erase(): http://www.cplusplus.com/reference/string/basic_string/erase/
Or you could just skip the leading whitespace if it is present.

1
2
3
4
5
#include <iomanip>

...

   getline(fin >> std::ws, First_Name);

Topic archived. No new replies allowed.