input and output stream
- Description: IO objects have no copy or assignment operations, and there are many flag bits that can determine the current state of IO
console input and output
- mainly
cin
withcout
- The standard library will be
cin
associatedcout
with cin, and the cout buffer will also be flushed when using cin
file input and output
file mode
- Classification
- in: open for reading
- out: open for writing
- app: Before each write operation, locate the end of the file
- ate: After opening the file, immediately locate the end of the file
- trunc: truncate file
- binary: run io in binary mode
- illustrate
- Only set out mode on
ofstream
orfstream
object - Only if the in mode is set on the
ifstream
orfstream
object - The trunc mode can only be set when the out mode is also set.
- Only using out mode will overwrite the content of the original file
- Only set out mode on
- Note: Use the open function to open the input and output stream, and use close to close it. Of course, for the declared variable, it can be closed because the object is destroyed, but it is recommended to close it manually as much as possible to prevent subsequent misoperations
code
void test() { vector<string> words; string s; char ch[1024]; ifstream infile("text.txt", ios::in); ofstream ofile("sentence.txt", ios::out); if (ofile) { // 按行读入 while (infile.getline(ch, 1024)) { cout << ch << endl; ofile << ch << endl; } infile.close(); ofile.close(); } infile.open("text.txt", ios::in); ofile.open("words.txt", ios::out); if (ofile) { // 按单词读入(遇到空格、换行、制表符等都会视为一个单词的结束) while (infile >> s) { cout << s << endl; ofile << s << endl; } infile.close(); ofile.close(); } }
string stream
Introduction
- Three classes are defined in the sstream header file to support memory IO,
istringstream
read data fromostringstream
string, write data to string, andstringstream
support the above two operations code
void test() { vector<string> words; string s; char ch[1024]; ifstream infile("contact.txt", ios::in); unordered_map<string, vector<int>> infos; while (getline(infile, s)) { string key; vector<int> vec; int tmp = 0; istringstream is(s); is >> key; // 构造一个包含字符串的读入缓冲区,然后可以从这个缓冲区中读取所需要的信息 while (is >> tmp) { vec.push_back(tmp); } infos[key] = vec; cout << s << endl; } cout << "=====infos======" << endl; ostringstream os; for (auto it = infos.begin(); it != infos.end(); it++) { os << "key is : " << it->first << ", value is : "; for (auto & num : it->second) os << num << " "; cout << os.str() << endl; os.str(""); //os.clear(); //这句话只是清空缓冲区的标志位,并没有清空缓冲区的内容 } }
Content in contact
AA 1 4 7 BB 2 5 8 CC 3 6 9