Strings
A 'string' is a sequence of 0 or more characters. That means that strings can be used to represent words, sentences, an entire document or single characters. In general if you know you are only going to use a single character you should use the 'char' type as it's more efficient.
Difference between "a"
and 'a':
When you assign a value to a string variable you must use double-quotes around the value like: "Hello World". Double-quotes tells the compiler
that the constant "Hello World" is a string and not a char.
That might be obvious in this case since more than one character is
being used, you couldn't assign "Hello World" to what's the big
deal? Well you can assign a single character to a char and
you can also assign a single character to a string, so how does the
compiler know the difference? It knows because you tell it
with the types of quotes you use. Using single quotes means
the constant is a char like: 'H'.
char letter = 'a'; //
OK
char letter = "a"; // ERROR: can't
assign a string to a char
string word =
"a" // OK
string word = 'a' // ERROR:
can't assign a char to a string
str( ) function:
Often you will need to convert a variable of some type to a string
to display in a message to the user, or to save to a file.
You can convert any built-in type to a string with the
str() function. This function takes as it's argument any
variable and returns a string representation of that
variable.
int showDouble(double num)
{
string msg = str( num );
PostMessage( "Your number is: " +
msg );
}
This function displays a message containing the number the user passed to it. For example if you passed it the number 2.71828 the output would be:
Message: Your number is: 2.71828
10 bonus points to anyone who knows what the number is.
Converted from CHM to HTML with chm2web Pro 2.82 (unicode) |