官术网_书友最值得收藏!

C++ Strings

In the previous chapter, we briefly mentioned Strings and we learned that a String can hold alphanumeric data – anything from a single character to a whole book. We didn't look at declaring, initializing, or manipulating Strings, so let's do that now.

Declaring Strings

Declaring a String variable is simple. It is the same process that we used for other variables in the previous chapter: we state the type, followed by the name:

String levelName;

String playerName;

Once we have declared a String, we can assign a value to it.

Assigning a value to a String

To assign a value to a String, just like regular variables, we simply put the name, followed by the assignment operator, and then the value:

levelName = "DastardlyCave";

playerName = "John Carmack";

Note that the values need to be enclosed in quotation marks. Just like regular variables, we can also declare and assign values in a single line:

String score = "Score = 0";

String message = "GAME OVER!!";

In the next section, we will see how we can change the values of our String variables.

Manipulating Strings

We can use the #include <sstream> directive to give us some extra manipulation options for our Strings. The sstream class allows us to "add" some Strings together. When we add Strings together, this is known as concatenation:

String part1 = "Hello ";

String part2 = "World";

sstream ss;

ss<< part1 << part2;

// ss now holds "Hello World"

In addition to this, by using sstream objects a String variable can even be concatenated with a variable of a different type. The following code starts to reveal how Strings might be useful to us:

String scoreText = "Score = ";

int score = 0;

// Later in the code

score ++;

sstream ss;

ss<<scoreText<< score;

// ss now holds "Score = 1"

In the preceding code, ss is used to join the content of scoreText with the value from score. Note that although score holds an int value, the final value held by ss is still a String that holds an equivalent value; in this case, "1".

Tip

The << operator is one of the bitwise operators. C++, however, allows you to write your own classes and override what a specific operator does within the context of your class. The sstream class has done this to make the << operator work the way it does. The complexity is hidden in the class. We can use its functionality without worrying about how it works. If you are feeling adventurous, you can read about operator overloading at http://www.tutorialspoint.com/cplusplus/cpp_overloading.htm. You don't need any more information in order to continue with the project.

Now that we know the basics of C++ Strings and how we can use sstream, we will look at how we can use some SFML classes to display them on the screen.

主站蜘蛛池模板: 湘乡市| 河曲县| 柯坪县| 灵山县| 伽师县| 连城县| 沙洋县| 江津市| 澄迈县| 剑河县| 赫章县| 大足县| 昆山市| 固安县| 浙江省| 永平县| 萨迦县| 观塘区| 普安县| 青冈县| 东乡族自治县| 准格尔旗| 武川县| 宝兴县| 吉林省| 忻州市| 色达县| 时尚| 河池市| 开原市| 缙云县| 攀枝花市| 藁城市| 马龙县| 繁峙县| 明光市| 龙里县| 康保县| 永修县| 泾阳县| 静乐县|