C/C++流操作(文件,字符串)

C++输入输入流
2008-05-23 01:01

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值