曲径通幽论坛

标题: 使用字符串 [打印本页]

作者: beyes    时间: 2011-6-21 00:03
标题: 使用字符串
在 C++ 里使用字符串,必须先把 string 头文件包括到程序里,该文件定义了必要的功能。C++ 字符串变量的声明和 C 不太一样,它的声明形式为:
std::string strval;
strval = "hello world";

还可以用字符串连接操作符 '+' 将字符串变量所代表的字符串连接起来。

测试代码
[C++] 纯文本查看 复制代码
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
    std::string str1, str2, str3, str4;

    str1 = "hello";
    str2 = "cpp";
    str3 = "world";

    str4 = str1 + " " + str2 + " " + str3;

    cout << "Press enter to continue" << endl;
    cin.get();

    cout << str4 << endl;

    return 0;
}

运行输出:
$ ./strtest
Press enter to continue

hello cpp world





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2