[ fromfile: strings.xml id: stlstrings ]
When working with string data in C++, you have three choices.
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; }
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>
The same example, rewritten to use Qt instead of STL, is shown in Example 1.8.
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; }
Define QTextStreams that look like C++ standard iostreams. | |
not iostream, QTextStream::readLine()! |
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |