Jump to content

Programming Fundamentals/Strings/C++

From Wikiversity

strings.cpp

[edit | edit source]
// This program splits a given comma-separated name into first and last name
// components and then displays the name.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C%2B%2B_Programming

#include <iostream>
#include <string>

using namespace std;

string getName();
string getLast(string name);
string getFirst(string name);
void displayName(string first, string last);
string lTrim(string text);

int main()
{
    string name;
    string last;
    string first;

    name = getName();
    last = getLast(name);
    first = getFirst(name);
    displayName(first, last);
}

string getName()
{
    string name;
    int index;

    do
    {
        cout << "Enter name (last, first):" << endl;
        getline (cin, name);
        index = name.find(",");
    } while (index < 0);
    
    return name;
}

string getLast(string name)
{
    string last;
    size_t index;

    index = name.find(",");
    if(index == string::npos)
    {
        last = "";
    }
    else
    {
        last = name.substr(0, index);
    }
    
    return last;
}

string getFirst(string name)
{
    string first;
    size_t index;

    index = name.find(",");
    if(index == string::npos)
    {
        first = "";
    }
    else
    {
        first = name.substr(index + 1, name.length() - index - 1);
        first = lTrim(first);
    }

    return first;
}

void displayName(string first, string last)
{
    cout << "Hello " << first << " " << last << "!" << endl;
}

string lTrim(string text)
{
    while(text.substr(0, 1) == " ")
    {
        text.erase(0, 1);
    }
    
    return text;
}

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own C++ compiler / interpreter / IDE.

See Also

[edit | edit source]