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

    • Used mainly when programming with C library code

    • An important source of runtime errors.

    • Should be avoided.

  2. Standard Library string

  3. QString - preferred over STL strings because:

    • Has a more extensive API making it easier to use.

    • Has built-in support for the Unicode standard for easier internationalization.

    • Makes more efficient use of memory resources.

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.


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>

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()!