C++ Stream

本文深入探讨了C++中基于字符串的输入输出操作,包括istringstream如何从字符串读取特定单词和所有令牌,以及ostringstream如何将输出写入字符串缓冲区。通过实例展示了istringstream和ostringstream的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载

C++的输入输出分为三种:

  • 基于控制台的I/O
    基于控制台的I/O
  • 基于文件的I/O
    基于文件的I/O
  • 基于字符串的I/O
    基于字符串的I/O

用法

#include <sstream>
// isstringstream

#include <sstream>
// 1. istringstream

// 1.1 read specific word tokens from a string
istringstream input("Jenny Smith 8675309"); // initialize a istringstream object
string first, last;
int phone;
input >> first >> last; // first="Jenny", last="Smith"
input >> phone; // 8675309

// 1.2 read all tokens from a string
istringstream input2("To be or not to be");
string word;
while (input2 >> word) {
    cout << word << endl; // To \n be \n or \n not \n ...
}

// 1.3 read a string line by line
string line;
while (getline(input, line)){
    istringstream tokens(line);
    // ...
}

// 2. ostringstream
// An ostringstream lets you write output into a string buffer.
int age = 42, iq = 95;
ostringstream output;
output << "Zoidberg's age is " << age << endl;
output << " and his IQ is " << iq << "!" << endl;
string result = output.str();

//3. STDIN
int age;
cin >> age;

// always use getline is better
string name;
getline(cin, name);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值