What is stream?

String Stream

#include <iostream>
#include <sstream>
 
int main()
{
    std::ostringstream oss("Hello", std::ostringstream::ate);
    std::cout << oss.str() << std::endl; // Hello
    oss << 100;
    std::cout << oss.str() << std::endl; // Hello100
    return 0;
}

Types matters! The operator returns the stream itself so that we can call them in a chain.

State Bit

  • iss.good() bool: true
  • iss.fail() bool: false
  • iss.eof()
  • iss.bad()
#include <iostream>
#include <sstream>
int main()
{
    std::ostringstream oss;
    std::istringstream iss;
    int a;
    std::cout << iss.eof() << std::endl; // 0
    iss >> a;
    std::cout << iss.fail() << " " << iss.eof() << std::endl; // 1 1
    return 0;
}

cout and cin

How to deal with? (The delimiter will be skipped and discarded)
(Though, it will not skip a leading delimiter!)

std::endl

/n + flush.

std::istringstream iss("   hello");
std::string s;
iss >> std::ws >> s;   // 跳过前导空白字符
std::cout << s;        // 输出 "hello"
std::cout << std::boolalpha;
std::cout << true << " " << false << std::endl;
// 输出:true false
 
std::cout << std::noboolalpha;
std::cout << true << " " << false << std::endl;
// 输出:1 0
#include <iomanip> // 头文件!
 
double pi = 3.1415926535;
std::cout << std::setprecision(3) << pi << std::endl;
// 输出:3.14(默认是有效数字)
 
std::cout << std::fixed << std::setprecision(3) << pi << std::endl;
// 输出:3.142(保留小数位数)