1.8.  Strings

[ fromfile: strings.xml id: stlstrings ]

When working with string data in C++, you have three choices.

  1. const char*, or C-style strings, which are used mainly when you are interfacing with C libraries, and rarely otherwise. They are a frequent source of runtime errors and should be avoided.

  2. string, from the C++ standard library, which is available everywhere.

  3. QString, which is preferred over STL strings, because it has a richer API and is easier to use. Its implementation supports lazy copy-on-write (or implicit sharing, explained later in Section 11.5) so functions can receive QString arguments and return QStrings by value without paying the penalty of allocating and copying the string's memory each time. Further, QString's built-in support for the Unicode standard facilitates internationalization.

Example 1.7 demonstrates basic usage of STL strings.

Example 1.7. src/generic/stlstringdemo.cpp

#include <string>
#include <iostream>

int main() {
    using namespace std;
    string s1("This "), s2("is a "), s3("string.");
    s1 += s2;  1
    string s4 = s1 + s3;
    cout << s4 << endl;
    string s5("The length of that string is: ");
    cout << s5 << s4.length() << " characters." << endl;
    cout << "Enter a sentence: " << endl;
    getline(cin, s2);  2
    cout << "Here is your sentence: \n" << s2 << endl;
    cout << "The length of your sentence is: " << s2.length() << endl;
    return 0;
}

1

concatenation

2

s2 will contain an entire line.


Here is the compile and run:

src/generic> g++ -Wall stlstringdemo.cpp 
src/generic> ./a.out
This is a string.
The length of that string is 17
Enter a sentence:
20 years hard labour
Here is your sentence:
20 years hard labour
The length of your sentence is: 20
src/generic>

Observe that we used

getline(cin, s2)

to extract a string from the standard input stream. The same example, rewritten to use Qt instead of STL, is shown in Example 1.8. It produces exactly the same output.

Example 1.8. src/qstring/qstringdemo.cpp

#include <QString>
#include <QTextStream>

QTextStream cout(stdout);  1
QTextStream cin(stdin);

int main() {
    QString s1("This "), s2("is a "), s3("string.");
    s1 += s2;  // concatenation
    QString s4 = s1 + s3;
    cout << s4 << endl;
    cout << "The length of that string is " << s4.length() << endl;
    cout << "Enter a sentence with whitespaces: " << endl;
    s2 = cin.readLine();   2
    cout << "Here is your sentence: \n" << s2 << endl;
    cout << "The length of your sentence is: " << s2.length() << endl;
    return 0;
}

1

Define QTextStreams that look like C++ standard iostreams.

2

not iostream, QTextStream::readLine()!


Observe that, this time, we used

s2 = cin.readLine()

to extract a QString from the standard input stream.