47.6k views
0 votes
ProcessName2

Modify your solution to the previous ProcessName exercise so that it re-prompts until the user types a name that is at least 5 letters total in length and has at least one space in it. '



Type your name: Joe
Error, must be at least 5 chars with a space.
Type your name: O K!
Error, must be at least 5 chars with a space.
Type your name: what
Error, must be at least 5 chars with a space.
Type your name: Tyler Durden
Your name is: Durden, T.

User Stombeur
by
4.8k points

2 Answers

7 votes

Step-by-step explanation:

This is easily solvable with a for loop. Something like:

(I assume c++)

#include <iostream>

#include <string>

int main() {

take_input: //tag

std::string input;

cin >> input; //take the input

int spaceCount = 0;

char checking;

for(unsigned int i = 0; i == input.length(); ++i) {

checking = spaceCount[i];

if(checking == ' ')

spaceCount++;

}

if(spaceCount >= 1 && input.length >= 5)

std::cout << "Your name is " + input;

else

goto take_input; // reasks for input if the conditions are not met

return 0;

};

**remove all spaces before using the code, the if statements are messed up

User Malcolm Groves
by
4.7k points
4 votes

Final answer:

You need to create a loop that continues to prompt for a name until it meets the required conditions: being at least 5 characters long and containing a space. Once a valid name is entered, the code should format and display the name with the surname first followed by the initial. Pseudocode is provided to illustrate the concept.

Step-by-step explanation:

The task at hand is one that requires minor modifications to a piece of code you've worked on previously. You need a loop that continuously prompts the user to input their name until the entered name meets the specific criteria: being at least five characters long and including at least one space. Once the valid input is received, the name is to be formatted with the surname appearing first, followed by a comma, and the first initial of the first name.

To achieve this, you could use a while loop that checks the length of the name and the presence of a space using the len() function and the in keyword. Once a suitable name is entered, the loop would end and the name would be formatted accordingly.

Here's a pseudocode example of how this might look:

while True:
name = input('Type your name: ')
if len(name) >= 5 and ' ' in name:
break
print('Error, must be at least 5 chars with a space.')
surname, firstname = name.split(' ', 1)
formatted_name = surname + ', ' + firstname[0].upper() + '.'
print('Your name is:', formatted_name)

Note that the above pseudocode needs to be translated into the programming language you're using. Remember to ensure that any input with more than one space is handled properly and that you're capturing the correct parts of the name for formatting.

User Tales
by
5.4k points