文章

Streams

Streams

stream: an abstraction for input/output. Streams convert between data and the string representation of data.

std::coutis an output stream .It has type std::ostream

Two ways to classify streams

By Direction:

  • Input streams
  • Output streams
  • Input/Output streams

    By Source or Destination:

  • Console streams
  • File streams
  • String streams

Output Streams

console

1
std::cout << 5 << std::endl;

file streams

1
std::ofstream out(“out.txt”)

Input Streams

  • Each » ONLY reads until the next Whitespace
    • Whitespace = tab, space, newline
  • Everything after the first whitespace gets saved and used the next time std::cin » is called
    • The place its saved is called a buffer!

      When things go wrong

      两个例子

      1
      2
      3
      4
      5
      6
      7
      8
      9
      
      string str;  
      int x;  
      string otherStr;
      std::cin >> str >> x >> otherStr;  
      //what happens if input is blah blah blah?  
      std::cout << str << x << otherStr;
      //once an error is detected, the input stream’s  
      //fail bit is set, and it will no longer accept  
      //input
      
1
2
3
4
5
6
int age; double hourlyWage;  
cout << "Please enter your age: ";  
cin >> age;  
cout << "Please enter your hourly wage: ";  
cin >> hourlyWage;  
//what happens if first input is 2.17?

std::getline()

1
2
3
// Used to read a line from an input stream  
// Function Signature  
istream& getline(istream& is, string& str, char delim);

In contrast:

  • “»” only reads until it hits
    whitespace (so can’t read a
    sentence in one go)
  • BUT “»” can convert data to
    built-in types (like ints) while
    getline can only produce strings.
  • AND “»” only stops reading at predefined whitespace while getline can stop reading at any delimiter you define ==IMPORTANT==: Don’t mix » with getline!
  • reads up to the next whitespace character
    and does not go past that whitespace
    character.

  • getline reads up to the next delimiter (by
    default, ‘\n’), and does go past that delimiter.
  • TL;DR they don’t play nicely

    String streams

    If you only want to read OR write data:

  • Read only: std::istringstream
  • Give any data type to the istringstream, it’ll store it as
    a string!
  • Write only: std::ostringstream
  • Make an ostringstream out of a string, read from it
    word/type by word/type!
  • Follows same patterns as the other i/ostreams!
本文由作者按照 CC BY 4.0 进行授权