文章

lec1 Streams

none

streams

overview

  • interact with some devices
    • console & keyboard
    • files
    • pipelines
    • sockets
  • stream is a unified interface.
    • in all devices do the same thing
    • for many interactions, stream provide a unified interface
  • two challenge
    • we need to retrieve/send data from the source in string form
    • we need to convert between data in our program and its string representation
  • streams provide a unified interface for interacting with external iput
    • just imagine a stream to be a character buffer that automatically interacts with the external source
    • streams also convert variables to a string form that can be written in the buffer
    • we use » & « to interacts with streams interface
  • 我们只需要关注如何使用»和«,想象streams是一个buffer即可,别的无需考虑

string stream

  • output stream
    • each streams has it’s own buffer
    • why streams instead of characters buffer?
      • streams can read a integer from it’s buffer, character buffer cann’t do it
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
      #include <iostream>
      #include <sstream>
    
      int main () {
          std::ostringstream oss("Ito-En Green Tea", std::stringstream::ate);
          std::cout << oss.str() << std::endl;
          oss << "16.9 Ounces";
          std::cout << oss.str() << std::endl;
          return 0;
      }
    
    • if we don’t use std::stringstream::ate, output will be 16.9 Ouncesn Tea.

    • oss << 16.9 << " Ounces; means number 16.9 will convert to chars(‘1’, ‘6’, ‘.’, ‘9’ and so on) in the buffer intead of double number

  • input stream
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
      #include <iostream>
      #include <sstream>
      int main () {
          std::istringstream iss("16.9 Ounce");
          double amount;
          std::string unit;
          iss >> amount;
          amount /= 2;
          iss >> unit;
          std::cout << "amount: " << amount << " unit: " << unit << "\n";
      }
    
    • input stream 可以自动将流里的东西转化成一些值,这些值由 » 指向的变量决定,如果上面我把amount的类型改成int,那么unit得到的值就会是”.9”
    • 最常见的分隔符是空格,可以想象成 » 操作的时候流遇到空格就切一下

state bits

input/output streams

manipulators

本文由作者按照 CC BY 4.0 进行授权

热门标签