(1)经常用到的是就是文件输入输出流:ifstream, ofstream。它们的用法也很简单。举个将一个文件复制到另一个文件的例子:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("in.file");
ofstream fout("out.file");
string str;
while(getline(fin, str, '/n'))
fout << str << endl;
return 0;
}
(2)字符串输入输出流:istringstream, ostringstream。举个例子:输入一行字符串,以空格为分隔符进行输出:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<string> vect;
string line;
getline(cin, line, '/n');
// cout << line << endl;
istringstream iss(line);
string word;
while(iss >> word)
vect.push_back(word);
vector<string>::iterator it = vect.begin();
while(it != vect.end())
{
cout << *it << endl;
it++;
}
return 0;
}
输入一行的double型数,以空格为分隔进行输出:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<double> vect;
string line;
getline(cin, line);
// cout << line << endl;
istringstream iss(line);
double d;
while(iss >> d)
vect.push_back(d);
vector<double>::iterator it = vect.begin();
while(it != vect.end())
{
cout << *it << endl;
it++;
}
return 0;
}
举个ostringstream的例子:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
int i;
double d;
cin >> i >> d;
cin >> ws; //从当前的读取位置去掉所有的空格
string buf;
getline(cin, buf);
ostringstream os;
os << "integer = " << i << endl;
os << "double = " << d << endl;
os << "string = " << buf << endl;
string result = os.str();
cout << result;
return 0;
}
注意:去掉 cin >> ws, cin.getline(buf,SZ)依然会读入一行的内容,只不过它会包含空格而已。你说的没有输入,可能是你前面在输入整数和浮点数的时候都回了车,例如:
12
12.1
这个时候没有cin>>ws语句,cin.getline(buf,sz)就会读入一空行。如果你把整数、浮点数和字符串都输入在一行,如:
12 12.1 test
这时你可以看到如果有cin>>ws语句,buf中的内容是"test"。如果没有cin>>ws语句,buf中的内容是" test"( 多了一个空格).
ostrstream os( buf, SZ, ios::app)是将buf所包含的字符串(最长为SZ)放入rdbuf()中。如果buf是空,就是将一空字符串放入其中(既什么都不放)
另一种写法:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
int i;
double d;
cin >> i >> d;
cin.get(); //接收'/n'
//cin >> ws; //从当前的读取位置去掉所有的空格
string buf;
getline(cin, buf);
ostringstream os;
os << "integer = " << i << endl;
os << "double = " << d << endl;
os << "string = " << buf << endl;
string result = os.str();
cout << result;
return 0;
}