[ fromfile: strings.xml id: stlstrings ]
When working with string data in C++, you have three choices.
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.
string
, from the C++ standard library, which is available everywhere.
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 QString
s 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; 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); cout << "Here is your sentence: \n" << s2 << endl; cout << "The length of your sentence is: " << s2.length() << endl; return 0; }
<include src="src/generic/stlstringdemo.cpp" href="src/generic/stlstringdemo.cpp" id="stlstringdemo" mode="cpp"/>
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); 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(); cout << "Here is your sentence: \n" << s2 << endl; cout << "The length of your sentence is: " << s2.length() << endl; return 0; }
<include src="src/qstring/qstringdemo.cpp" href="src/qstring/qstringdemo.cpp" id="qstringdemocpp" mode="cpp"/>
Observe that, this time, we used
s2 = cin.readLine()
to extract a QString from the standard input stream.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |