Problem 3 (DO IT YOURSELF!) – Substrings
Write a program that asks the user to enter his full name. The program should display first name and last name.
Example:
Full name is Ahmed Mohamed
First name is Ahmed
Last name is Mohamed
//my solution
#include <iostream>
#include <string>
using namespace std;
void main()
{
string full_name, first_name, last_name;
cout << "enter full name" << endl;
cin >> full_name;
getline(cin, full_name);
int start_position = 0;
int mid_pos = full_name.find(' ');
int last_pos = mid_pos - start_position;
cout << "first name is "<<full_name.substr(start_position,mid_pos) << endl;
cout << "Last name is "<<full_name.substr(mid_pos) << endl;
}
//my problem is when i run the code first name does not appear
#include <iostream>
#include <sstream>
int main()
{
std::cout << "Enter your full name (first and last): ";
std::string full_name;
std::getline(std::cin, full_name);
std::cout << "\nYour full name: " << full_name << "\n";
// create a string stream for extracting first and last names
std::istringstream iss(full_name);
std::string first_name;
iss >> first_name;
std::cout << "Your first name: " << first_name << "\n";
std::string last_name;
iss >> last_name;
std::cout << "Your last name: " << last_name << "\n";
}
Enter your full name (first and last): Joe Schmoe
Your full name: Joe Schmoe
Your first name: Joe
Your last name: Schmoe