C++ - Chapter 3 - Working with Text


Text is the simplest (and most used) medium for generating output. Displaying text is also handy for debugging programs. With this in mind, it seems as useful to have a general understanding of what you can do with text and strings. If you followed the source code example from chapter 1, the "Hello World!" component of the output line is called a string. A string is a collection of characters. In the ASCII (American Standard Code for Information Interchange) system, there are 128 characters (95 of them printable to screen or files.) In the Extended ASCII system, there are a potential 256 characters to utilize.

Definitions (in layman's terms)

ASCII (American Standard Code for Information Interchange) is the standardized character encoding based on the English alphabet with a range of 128 characters (standard) or 256 characters (extended). ASCII is used in digital systems to display and manipulate binary data as characters.

Strings are an array of characters.

Escape Characters are special characters used to represent characters that cannot be expressed literally in C++ (such as quotation marks and backslashes).

#include <iostream>
#include <string>

using namespace std;

int main (void)
	string name;
	string greeting = "This computer is being used by: ";

	cout<<"Enter your Name: ";

	    <<endl<<"Hello "<<name.c_str();

	return 0;
Enter your Name: Archon
This computer is being used by: Archon
Hello Archon

#include <string> is the C++ library header file needed for access to the string class. The string header file give us the type definition, "string" which allows us to declare the variables, "name" and "greeting". In the declaration line, we have initialized the string variable, "greeting" to the string literal, "This computer is being used by: ".

We use standard input to store the username in the variable, "name". The line, cout<<greeting.c_str()<<name.c_str()<<endl<<"Hello "<<name.c_str(); contains a subelement, c_str(). This is a function contained in the string class that converts a string to a character pointer and is very useful for many applications, such as storing a filename for opening or for simple output as in this case.

Once we get into Object Oriented Programming, you will recognize the format of, for example, name.c_str(). In brief, "name" is the variable name of a string class and c_str() is a function member of the class, string. The intermediate period tells the compiler that c_str() is a member of the string class named, "name".

< Back - Variables Index Next - Loops >