您的位置:首页 > 编程语言 > C语言/C++

C++标准输入输出流stream介绍

2017-03-29 13:03 381 查看
This chapter begins by giving you more insight into the features provided by the << and >> operators. It then moves on to introduce the notion of data files and shows you how to implement file-processing applications.

<< >>用于窗口的输入输出。

包含的头文件是istream 和ostream

还有文件的输入输出,包含的头文件是ifstream 和ofstream

下面举一个例子,表示文件的操作。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
string promptUserForFile(ifstream &infile, string prompt = "")
{
while (true) {
cout << prompt;
string filename;
getline(cin, filename);
infile.open(filename.c_str());
if (!infile.fail()) return filename;
infile.clear();
cout << "Unable to open that file. Try again." << endl;
if (prompt == "") prompt = "Input file: ";
}
}

int main(int argc, char *argv[])
{
ifstream infile;
promptUserForFile(infile, "Input file: ");
char ch;
while (infile.get(ch)) {
cout.put(ch);
}
infile.close();
return 0;
}


也可以一次读入一行,那么while循环如下

string line;
while (getline(infile, line)) {
cout << line << endl;
}


sstream和string相联系。

可以这样初始化

istringstream stream(str);


The following function, for example, converts an integer into a string of decimal digits:

string integerToString(int n) {
ostringstream stream;
stream << n;
return stream.str();
}

int getInteger(string prompt) {
int value;
string line;
while (true) {
cout << prompt;
getline(cin, line);
istringstream stream(line);
stream >> value >> ws;
if (!stream.fail() && stream.eof()) break;
cout << "Illegal integer format. Try again." << endl;
}
return value;
}


继承关系图



void copyStream(istream &is, ostream &os) {
char ch;
while (is.get())
os.put(ch);
}


In any event, reading .h files is a programming skill that you will need to cultivate if you want to become proficient in C++.

复习题。

1. 字符,字符串,和文件。

4. 操作符。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: