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;
}
相关推荐
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境2 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境2 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴3 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境5 天前
C++ 的Eigen 库全解析
c++
卷无止境5 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴5 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18007 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴7 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake