The std::string Class

Chris Wild & Steven Zeil

Last modified: May 28, 2014

Contents:
1. Description
2. Example
3. Tips - I/O
3.1 Read characters until a whitespace character is found
3.2 Read until the end of line.
3.3 Read until a special character is found.

1. Description

2. Example


#include <string>
#include <iostream>

using namespace std;

int main()
{
    string firstName, lastName, fullName;
    string greeting("Hello ");


    cout << "What is your name (first last separated by a space)? ";
    cin >> firstName >> lastName;
    greeting.append(lastName);
    greeting.append(", " + firstName);
    string banner(greeting.length() + 4,'$'); // construct string with bunch of '$'s
    cout << banner << endl;
    cout << "$ " << greeting + " $" << endl;
    cout << banner << endl << endl;
    if(firstName < lastName)
        cout << "your first name is alphabetically before your last\n";
    else
        cout << "your first name is alphabetically after your last\n";
    return 0;
}

Sample Execution

What is your name (first last separated by a space)? chris wild
$$$$$$$$$$$$$$$$$$$$$
$ Hello wild, chris $
$$$$$$$$$$$$$$$$$$$$$

your first name is alphabetically before your last


3. Tips - I/O

There are three approaches used for reading strings.

3.1 Read characters until a whitespace character is found

3.2 Read until the end of line.

The following program should produce the same output as the first program.

stringRead.cpp

3.3 Read until a special character is found.

stringRead2.cpp


So which method of inputting strings is the best to use?

Remember always that >> skips over leading whitespace and stops before (but does not consume) trailing whitespace. getline preserves leading whitespace and consumes (discards) its stopping character.