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;
}
相关推荐
不会代码的小猴8 小时前
21. 泛型编程上
开发语言·c++·笔记·算法
青瓦梦滋9 小时前
传输层UDP/TCP协议
linux·网络·c++·网络协议·tcp/ip·udp
一只旭宝9 小时前
细讲C加加【9】C++ std::function与std::bind详解|仿函数、绑定器、类成员绑定、占位符、成员偏移指针
开发语言·c++·算法
Lhan.zzZ11 小时前
在 Visual Studio 2022 中打造可扩展的动态链接库模块:从零搭建到原理解析
开发语言·c++·visual studio
zh路西法13 小时前
【3D SLAM源码解读系列】(二)Small_gicp——5 个积木搭出最优点云配准
c++·pcl·icp·fastgicp·smallgicp·gicp
fpcc15 小时前
ubuntu26环境下的开发环境安装处理
c++·并行编程
charlie11451419116 小时前
Cinux · 第一次跳进 Ring 3:用户态与特权隔离
开发语言·c++·操作系统·开源项目
别动我齐刘海16 小时前
机器学习基础2——C++、OpenCV、点云、Open3D
c++·人工智能·opencv·机器学习·计算机视觉·机器人·ros2
躺不平的理查德17 小时前
Windows C++ 第三方库使用流程备忘录--OpenCV
开发语言·c++
余额瞒着我当琳17 小时前
C++STL容器string--迭代器,string的接口,string的遍历,访问方式
c++