Using the getline function

Feb 17, 2009 at 1:19am
I am trying to write a progam that takes a full name without spaces and prints the name on separate lines using the getline function. My program is not working. This is what I have:


#include<iostream>
#include<string>
using namespace std;

int main()
{
string str;
str = "Jane Sue Doe";
string str1;
string str2;
string str3;

cout << "First Name: ";
getline(cin, str1,'\n');
cout << "Middle name: ";
getline(cin, str2,'\n');
cout << "Last name: ";
getline(cin, str3,'\n');
return 0;
}


Instead of automatically filling in the First Name, Middle Name, and Last Name on separate lines it prompts me to do it.
Last edited on Feb 17, 2009 at 2:20am
Feb 17, 2009 at 2:56am
If you wanted to separate Jane Sue Doe into first middle and last name add a little loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    string str;
    str = "Jane Sue Doe";
    string name[3];

    int i = 0;   
    
    for(int j = 0; j < str.length(); j++)
    {
        if(str[j] != ' ') 
        {
		name[i] += str[j];
        }
	else
	{
		if( i < 3 )
			i++;
	}
    }


name[0] would be the first name name[1] the middle name ...
Last edited on Feb 17, 2009 at 2:57am
Feb 17, 2009 at 3:39am
Thanks so much for responding but for this assignment I am required to use the getline function. My output should be:

First Name: Jane
Middle Name: Sue
Last Name: Doe

My understanding is that the newline character sees a space as a return and will jump to the next line and read the next string.
Feb 17, 2009 at 3:45am
The only way to use the getline function would be for input. You could have the user input a name like this:
1
2
3
string str;
cout << "Enter a name: (Use spaces between first, middle, and last name)\n";
getline(cin, str);


and then run the name through the function and output the name like this:
1
2
3
cout << "First Name: " << name[0] << endl;
cout << "Middle Name: " << name[1] << endl;
cout << "Last Name: " << name[2] << endl;


With standard cin input (i.e. cin >> string;) a space is treated as a newline but with getline all of the data is collected until a newline is read. (Enter key is pressed)
Last edited on Feb 17, 2009 at 3:48am
Feb 17, 2009 at 4:02am
1
2
3
4
5
6
#include <sstream>
//...
string name, first, middle, last;
getline( cin, name ); // expects full name on a single line
istringstream os( name );
os >> first >> middle >> last;


However, why not just skip the use of getline:
1
2
string first, middle, last;
cin >> first >> middle >> last;
Last edited on Feb 17, 2009 at 4:03am
Feb 17, 2009 at 5:37am
Thanks again for your help. It still isn't working for me. I'll see what feedback I get from the instructor.
Feb 17, 2009 at 7:11am
Which incidentally is what you should have done in the first place.
Topic archived. No new replies allowed.