How do I get the first x characters of a string to be measured and printed out?

Viewed 34

I've been assigned a problem at school and it goes as follows:

Write a program that creates a login name for a user, given the user's first name, last name, and a four-digit integer as input. Output the login name, which is made up of the first five letters of the last name, followed by the first letter of the first name, and then the last two digits of the number (use the % operator). If the last name has less than five letters, then use all letters of the last name.

The sample output is:

Enter first name: John
Enter last name: Doe
Enter last 4 digits of social security number: 8457
Your login name: DoeJ57

So far this is my code:

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() 
{
   string firstName;
   string lastName;
   int ssn;
   int lastTwo;
   char firstCharacter;
   string lastNameLength;
   
   cout << "Enter first name:";
   cin >> firstName;
   cout << "Enter last name:";
   cin >> lastName;
   cout << "Enter last 4 digits of social security number:";
   cin >> ssn;
   
   firstCharacter = firstName.front();
   lastTwo = (ssn % 100);
   
   lastNameLength = lastName.length();
   cout << lastNameLength;
   return 0;
}

I tried measuring the length of the last name for it to print out but now I'm stuck on how to get the last name sized and then printed, any guidance is appreciated.

1 Answers

std::string has a substr() method for extracting a portion of the string. If you ask it for the 1st 5 characters, and the string is shorter than 5 characters, then the entire string will be returned. Which is exactly what your instructions ask for.

Try something more like this:

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

int main() 
{
   string firstName;
   string lastName;
   int ssn;
   
   cout << "Enter first name:";
   cin >> firstName;
   cout << "Enter last name:";
   cin >> lastName;
   cout << "Enter last 4 digits of social security number:";
   cin >> ssn;
   
   cout << lastName.substr(0, 5) << firstName.front() << ssn % 100;

   return 0;
}

Online Demo

Related