HELP with getline (string) !!

I have my program working perfectly but my professor just told me that I needed to use getline for the user to input their full name. I can't use cin>>x>>y>>z for the user input. Please help, I'm very new at c++ and very lost. Here is my full code.

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
  #include <iostream>
#include <string>
#include <iomanip>
using namespace std;

void LengthAndPosition(string, string, string ,string, int& , int&  , int&  , int& );
string full, first, middle, last;
int firstLength, lastLength,totalLength,commaPosition;

int main() {
    cout<<"Please enter your first name, middle initial, and last name: ";
    cin>>first>>middle>>last;
    full = first+middle+last;
    LengthAndPosition(full, first, middle, last, firstLength, lastLength, totalLength, commaPosition);
    cout<<"The "<<firstLength<<" characters of the first name are: "<<first<<endl;
    cout<<"The "<<lastLength<<" characters of the last name are: "<<last<<endl;
    cout<<"In the phone book, the name would be: "<<last<<", "<<first<<" "<<middle<<endl;
    cout<<"The length of the name is: "<<totalLength<<endl;
    cout<<"The comma is at position: "<<commaPosition<<endl;
    cout<<"After the swap, the last name is "<<first<<" and the first name is "<<last<<endl;
    return 0;
}

void LengthAndPosition(string full, string first, string middle, string last, int& firstLength, int&  lastLength, int&  totalLength, int&  commaPosition){
    firstLength = first.length();
    lastLength = last.length();
    totalLength = full.length();
    commaPosition = last.length();
}
Last edited on
you would use
1
2
3
4
5

getline(cin, first);
getline(cin, middle);
getline(cin, last);
I just tried that, and input the first name, middle initial, and last name but then the program just stopped.

I'm supposed to input a name like Bob D Smith and use getline and then the string would be split into first name, middle initial, and last name for further use in my program. I'm not sure how to do that.
It didn't stop responding, it was waiting on you to hit enter and type a new name.


Try this
http://www.cplusplus.com/reference/sstream/istringstream/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
// Using a string
std::string name;
std::cout << "Please, enter your first, middle and last name: ";
std::getline (std::cin,name);
// convert
string first, middle, last;
istringstream iss(name);
iss >> first;
iss >> middle;
iss >> last;
cout << first << ", " << middle << ", "  << last;
return 0;
}
Last edited on
Topic archived. No new replies allowed.