The STL String Class - Read or print using string
(Page 2 of 4 )
The extraction and insertion process for the streams is already implemented. This may be a little too advanced of a concept for you to comprehend currently, but to bring it to a more understandable level, this simply means you can read in a number from a file or from the console. Alternatively, just print the content of the string to the same destinations.
Use the insertion operator>> and extraction operator << to the respective devices. To print something on the console, use the cout (defined in the header iostream), or to read in, the cin. For more information about this, I recommend that you read my article about this titled "Basic I/O in C++" and after completing this article, also the rest of the series dedicated to the world of streams in C++. (This article is the third part of a ten-part series).
string text;
cin >> text;
cout << text;
If you find it hard to understand in which direction the operator should point, think of it as the direction the operator tells you from where to where the data "flows." The upper code will print out everything you write in until it hits a whitespace.
Observe, if you add in a number, for instance "23," that will appear in the string as 23. However if you assign the 23 to the stream directly, that will throw an error. This is because the input data from the console comes already as text, but the string does not have an assign operator for int. Therefore, you first must convert the number into a c style string, and only after that call the assign.
This can be achieved with many functions that remain from the days of C, like the sprint and atoi. However, there is a more efficient method in the world of C++ using the stream classes' streamstring. Nevertheless, this will be the subject of a future article, titled Using the stringstreams.
Reading a full line (or more precisely reading until a new line char occurs) is done with the getline function as follows:
string text;
getline(cin, text);
You may sometimes need to access a character at a specific position. You may do this the old way by using the [] operator and just trying to get the char at that position, or use the at() member function. The second also performs a validity check for the input, and if it is invalid, will throw an out_of_Range_Class exception that you may treat with a try/catch idiom. As a drawback, this additional step will have some performance penalty on the application. Generally use the [] solution only when the input's validity is assured. If you pass on an invalid input for the [] operator the result is undefined.
text[10]; //faster
text.at(10); // safer
If you are interested in the length of your string, you can obtain it by calling either the size or length() member functions.
text.length() == text.size();
Next: Checks, find, concatenation >>
More C++ Articles
More By Gabor Bernat