Zebra0.com

cpp stringsInput name as Last,First, break into first and last

Input name as Last,First, break into first and last

Input name as Last,First, break into first and last

// Programmer: Janet Joy
// input name as Last,First
// break into First and Last
#include "pch.h"
#include <iostream>
#include<string>
using namespace std;
int main()
{
	string name,last,first;
	cout << "Enter your name as Last,First:";
	getline(cin, name); //reads the whole line
	int pos = name.find(",");
	if (pos < 0) cout << "You did not enter your name correctly!\n";
	else {
		last = name.substr(0, pos); //from 0 up to the comma
		first = name.substr(pos + 1); //everything after the comma
		cout << "First = " << first << endl;
		cout << "Last = " <<last << endl;
	}
}

To Do:

  1. Run the program and verify that it works.
  2. Loop until they enter the name with a comma.
  3. Write a function that receives name and first and last by reference.
  4. If there is no comma, assume it is in the format First Last.

NEXT: Validating String as Social Security number