C++之string流与文件流

  • istrstream和ostrstream在98标准中废弃,取而代之的是istringstream和ostringstream,实现类似于C语言中sprintf和sscanf的效果
cpp 复制代码
#include <iostream>
#include <cstdio>
#include <sstream>
using namespace std;
int main(void){
    int i = 1234;
    double d = 56.78;
    char s[] = "hello";
#if 0
    char buf[100] = {0};
    sprintf(buf, "%d %lf %s", i, d, s);
    printf("%s\n", buf);
    char str[] = "100 1.23 world";
    sscanf(str, "%d %lf %s", &i, &d, s);
    printf("%d %lf %s\n", i, d, s);
#endif
    ostringstream oss;
    oss << i << ' ' << ' ' << d << ' ' << s;
    cout << oss.str() << endl;
    
    istringstream iss;
    iss.str("100 1.24 world");
    iss >> i >> d >> s;
    cout << i << ", " << d << ", " << s << endl;
    return 0;
}  

文件流

  • C++将文件看成是一个个字符在磁盘上的有序集合,用流来实现文件的读写操作
  • C++中用来建立流对象的类有ifstream(输入)、ofstream(输 出)、fstream(输入输出)
cpp 复制代码
#include <iostream>
#include <fstream>
using namespace std;
int main(void){
    int i = 1234;
    double d = 56.78;
    char s[] = "hello";
    ofstream ofs("a.txt");
    ofs << i << d <<s << endl;
    ofs.close();
    
    ifstream ifs("a.txt");
    int i2;
    double d2;
    string s2;
    ifs >> i2 >> d2 >> s2;
    cout << i2 << endl;
    cout << d2 << endl;
    cout << s2 << endl;
    return 0;
}
相关推荐
知识领航员15 小时前
蘑兔AI音乐深度实测:功能拆解、实测表现与适用场景
java·c语言·c++·人工智能·python·算法·github
jf加菲猫17 小时前
第21章 Qt WebEngine
开发语言·c++·qt·ui
码农-阿杰17 小时前
深入理解 synchronized 底层实现:从 HotSpot C++ 源码看对象锁与 Monitor 机制
开发语言·c++·
Szime17 小时前
深智微IC华润微代理:MCU选型与工业控制方案推荐
c++
叼烟扛炮18 小时前
C++ 知识点18 内部类
开发语言·c++·算法·内部类
汉克老师18 小时前
GESP5级C++考试语法知识(十五、分治算法(二))
c++·算法·排序算法·分治算法·gesp5级·gesp五级
汉克老师19 小时前
GESP6级C++考试语法知识(五、格雷码)
c++·算法·位运算·异或·gesp6级·gesp六级·格雷码
程序leo源20 小时前
C语言知识总结
c语言·开发语言·c++·经验分享·笔记·青少年编程·c#
沫璃染墨20 小时前
二叉搜索树完全指南:从核心原理到增删查改全实现
开发语言·c++
‎ദ്ദിᵔ.˛.ᵔ₎20 小时前
C++哈希表
数据结构·c++·散列表