C++的输入输出分为三种:
- 基于控制台的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);