0
char first[20], middle[20], last[20];
cout << "Enter you name (F/M/L or F/L) \n";
cin >> first;
cin >> middle;
cin >> last;

pretty simple, assignment is to write the code so that if the user enters "John smith" it will output "smith, John" and if they enter "John x. smith" it will output "smith, John x." the code here only works for 3 name entries, any way to tweak it into being able to read a two name entry while not messing up the three names?

3 Answers3

0

I think your problem with the two name case is, that cin wants three inputs for this. You can use std::getline to get a whole line from cin (so it blocks until the first enter). Then you can create a std::istringstream from this and extract three names. If there are only two, after the last extraction the stringstream will evaluate to false which you can then check with if(stream). (assuming the name of your stringstream is stream)

n314159
  • 4,990
  • 1
  • 5
  • 20
0

You can read in the whole line at once with std::getline() and then use something like this answer to count the words in the string.

That could look like:

unsigned int countWordsInString(std::string const& str) {
    std::stringstream stream(str);
    return std::distance(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>());
}

int main() {
    string full_name;
    unsigned numWords = 0;

    while (numWords != 2 && numWords != 3) {
        std::getline(std::cin, full_name); // Read the whole line into full_name
        numWords = countWordsInString(full_name);
        if ( num_words == 2 ) {
            // Read first/last from full_name
        } else if (num_words == 3) {
            // Read first/middle/last from full_name
        } else {
            std::cout << "Bad input. Input must be 'First Middle Last' or 'First Last'" << std::endl;
        }
    }
}
scohe001
  • 15,110
  • 2
  • 31
  • 51
0

Read the full name in a line and then use a string tokenizer to see how many words the name has. It would help you make a generic code and not just restrict to two or three word names.

Using above approach, you can have any number of words in the input name.

Hope this helps ! Have a good day..