C++篇:004

C++篇:004.综合案例

基于字符串的IO操作

1.iostream

istream 读取

ostream 写入

iostream 读写

2.fstream

ifstream 读取

ofstream 写入

fstream 读写

3.sstream

istringstream 读取

ostringstream 写入

stringstream 读写

#include <iostream>
#include <sstream>

void test01() {
	string s1 = "I love China";
	
	istringstream istr(s1);//创建对象
	
    /*
    while运行后,s1被分行输出:
    I
    love
    China
    */
	string s2;
	while(istr >> s2) {
		cout << s2 << endl;
	}
}

//test02效果与test01相同
void test02() {
    
    istringstream istr;
    
    istr.str("I love China");
    string s2;
    while(istr >> s2) {
		cout << s2 << endl;
    }
}

//把str中的数据赋给int和double(Amazing!)
void test03() {
    
    istringstream istr("100 3.15");
    int num;
    double num2;
    
    istr >> num;
    istr >> num2;
    cout << num << endl;
    cout << num2 << endl;
}

//ostringstream
void test04() {
    //初始化ostr
    ostringstream ostr("hello");
    //先创建ostr2,再用"world"覆盖ostr2内容
    ostringstream ostr2;
    ostr2.str("world");
    
    //ostr.str()可以返回ostr中的内容
    cout << ostr.str() << endl;
    cout << ostr2.str() << endl;
    
    //put()是从第一个字符开始覆盖,结果为"aello"
    ostr.put('a');
    cout << ostr.str() << endl;
    //多个替换,使用"<<",结果为"abcld"
    ostr2 << "abc";
    cout << ostr2.str() << endl;
}

//stringstream
void test05() {
    
    stringstream ss("China");
    stringstream ss2;
    ss2.str("beijing");
    
    cout << ss.str() << endl;
}

//stringstream可以进行类型转化
void test06() {
    //整型转化为字符串
    int num = 100;
    string str;
    stringstream ss;
    
    ss << num;
    ss >> str;
    cout << str << endl;
    
    //多次使用stringstream对象的时候,一定要先清空一下**********
    ss.clear();
    
    //c风格字符串转换为string
    char c[10] = "abc";
    ss << c;
    ss >> str;
    
    //字符串转换为整型
    string s2 = "200";
    
    ss.clear();
    
    ss << s2;
    ss >> num;
    cout << num << endl;
}

单词统计器

具体过程略

posted on 2025-10-15 22:28  Khalilll  阅读(3)  评论(0)    收藏  举报