码迷,mamicode.com
首页 > 编程语言 > 详细

C++中string类

时间:2015-08-25 15:44:03      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

1.C中通过字符数组来存储字符串,而C++中通过string类来存储并处理字符串。<string>

#include<string>
#include<iostream>

using namespace std;
 
int main()
{   
    string str1,str2;    //空字符串
    string str3 = "Hello C++!";        //初始化
    string str4("I am");    //初始化
    str2 = "Today";        //赋值
    str1 = str3 + " " +str4;    //组合字符串
    str1 += " 8 ";
    cout<<str1 + str2 + "!"<<endl;
    return 0;
}
/*
输出:
E:\myDocuments\GUN\C++>Demo.exe
Hello C++! I am 8 Today!

E:\myDocuments\GUN\C++>

*/

  两种初始化方法,直接用+和=操作。

2.文件读写<fstream>,它会自动包含<iostream>,书中建议如果是有cout和cin最好显示引入<iostream>

  ①为了读而打开一个文件,创建对象ifstream,用法与cin相同,数据是从磁盘到内存里面

  ②为了写而打开一个文件,创建对象ofstream,用法与cout相同,数据时从内存到外部磁盘中。

//copy one file to another ,a line at one time
#include<iostream>
#include<fstream>

using namespace std;
 
int main()
{   
    ifstream In("Demo.cpp");    //读取Demo.cpp文件
    ofstream Out("Demo2.cpp");    //写入文件Demo2.cpp文件
    string STR1;
    while(getline(In,STR1))
        Out<<STR1<<"\n";
    
    return 0;
}
/*
输出:
E:\myDocuments\GUN\C++>g++ Demo.cpp -o  Demo.exe

E:\myDocuments\GUN\C++>Demo.exe

E:\myDocuments\GUN\C++>dir
 驱动器 E 中的卷是 DATA
 卷的序列号是 EC10-1C79

 E:\myDocuments\GUN\C++ 的目录

2015-08-25  13:59    <DIR>          .
2015-08-25  13:59    <DIR>          ..
2015-08-25  13:58               333 Demo.cpp
2015-08-25  13:58           497,380 Demo.exe
2015-08-25  13:59               333 Demo2.cpp   --------------------新添的文件
2015-08-21  09:52               111 GUN.bat
               4 个文件        498,157 字节
               2 个目录 81,163,862,016 可用字节


*/

3.string对象具有动态特性,不必担心string的内存分配

  

//把一个文件的拷贝到一个string对象中
#include<iostream>
#include<fstream>
#include<string>

using namespace std;
 
int main()
{   
    ifstream In("Demo.cpp");    //读取Demo.cpp文件
    
    string STR,line;
    while(getline(In,line))
        STR += line + "\n";
    
    cout<<STR;
    
    return 0;
}
/*
输出:
E:\myDocuments\GUN\C++>g++ Demo.cpp -o  Demo.exe

E:\myDocuments\GUN\C++>Demo.exe
//把一个文件的拷贝到一个string对象中
#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main()
{
        ifstream In("Demo.cpp");        //读取Demo.cpp文件

        string STR,line;
        while(getline(In,line))
                STR += line + "\n";

        cout<<STR;

    return 0;
}
E:\myDocuments\GUN\C++>


*/

 

C++中string类

标签:

原文地址:http://www.cnblogs.com/hinice/p/4757171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!