1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int count_words(const string& s);
void assign_names(const string& name, int words, string& first, string& middle, string& last);
int main()
{
string name, first, middle, last;
int words;
cout << "Enter your name: ";
getline(cin, name);
words = count_words(name);
assign_names(name, words, first, middle, last);
cout << "First = " << first << endl
<< "Middle = " << middle << endl
<< "Last = " << last << endl;
system("pause");
return 0;
}
int count_words(const string& s)
{
int word_count = 0;
char current, last;
last = s[0];
current = s[1];
int index = 1;
if (!isspace(last))
word_count++;
while (index < s.length())
{
if ((!isspace(current)) && (isspace(last)))
word_count++;
last = current;
index++;
current = s[index];
}
return word_count;
}
void assign_names(const string& name, int words, string& first, string& middle, string& last)
{
int name_index = 0, first_index = 0, middle_index = 0, last_index = 0;
if (words == 2)
{
do
{
first[first_index] = name[name_index];
first_index++;
name_index++;
} while (name[name_index] != ' ');
name_index++;
do
{
last[last_index] = name[name_index];
last_index++;
name_index++;
} while (name_index < name.length());
}
else if (words == 3)
{
do
{
first[first_index] = name[name_index];
first_index++;
name_index++;
} while (name[name_index] != ' ');
name_index++;
do
{
middle[middle_index] = name[name_index];
middle_index++;
name_index++;
} while (name[name_index] != ' ');
name_index++;
do
{
last[last_index] = name[name_index];
last_index++;
name_index++;
} while (name_index < name.length());
}
}
|