I have to intput first, middle and last name of a person and the output should be last name, first initial and middle initial if the name has one, but I am having problems trying to take out the middle initial and when I don put a middle name the code prints last name, first initial and last initial any solutions?
#include <iostream>
#include <string>
using namespace std;
int main() {
/* Type your code here. */
string firstName, middleName, lastName, fullName;
getline(cin, fullName);
char firstSpace = fullName.find_first_of(' ');
char secondSpace = fullName.find_last_of(' ');
firstName = fullName.substr(0, firstSpace);
middleName = fullName.substr(fullName.find(' ') + 1 , fullName.find (' ') );
if (secondSpace < 0) {
lastName = fullName.substr(firstSpace);
cout << lastName + ", " + firstName.substr(0,1)+ "." << endl;
}
else{
lastName = fullName.substr(secondSpace + 1);
cout << lastName + ", " + firstName.substr(0,1) + "." + middleName.substr(0,1) + "." << endl;
}
return 0;
}