C++ fstream stringstream

时间:2020-12-12 10:23:20

一、文件输入输出

C/C++

输入:

freopen("in.cpp", "r", stdin);
fclose(stdin);

输出:

freopen("in.cpp", "r", stdout);
fclose(stdout);

C++

输入:

ifstream cin("in.cpp");

cin.close();

输出:

ofstream cout("out.cpp");

cout.close();

二、istringstream ostringstream 和 stringstream.

常用函数:

string str, s;

stringstream str;

stringstring str(s);

str.clear();

str.str(s);

Eg:

#include <sstream>
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std; string str, name, pnum;
string outstr; int main() {
ifstream cin("in.cpp");
ofstream cout("out.cpp");
stringstream imess;
stringstream omess;
while (getline(cin, str)){
imess.clear();
omess.str("");
imess.str(str); imess >> name;
omess << name << ":"; while(imess >> pnum) {
omess << " " << pnum;
}
cout << omess.str() << endl;
}
cin.close();
cout.close();
return 0;
}