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

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 
#include 
#include 

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;
}

继承关系图
C++标准输入输出流stream介绍_第1张图片

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. 操作符。



你可能感兴趣的:(abstraction,c++)