一、文件的读写
(1)输入输出重定向
命令行格式:c:>programoutputfile
即运行名为program。exe的可执行程序,用文件inputfile作为输入,用文件outputfile作为输出。
例如:
c:>addnumbers <number.txt >output.txt
从文件number.txt中读取数据,运行结果写入到output.txt中。
(2)标准库文件流
头文件:
ifstream类:istream的派生类,用来读入文件。
ofstream类:ostream的派生类,用来写入文件。
fstream类:iostream的派生类,用来输入输出(读写)。
使用例题:
#include<fstream>
using namespace std;
int main()
{
ifstream in("number.txt");
int number,sum=0;
in>>number;
while(number!=0)
{
sum+=number;
in>>number;
}
in.close();
ofstream out;
out.open("output.txt");//也可使用ofstream out("output.txt");一步完成
out<<"sum is:"<<sum<<endl;
out.close();
}
(3)字符串流
头文件:
istringstream:istream的派生类,用来从string对象中读取数据。
ostringstream:ostream的派生类,用来向string对象写入格式化的内容。
stringstream:iostream的派生类,即可以读取,又可以写入。
strm.str(),返回字符串流strm中保存的字符串的副本。
strm.str(s),将字符串s复制到字符串流strm中,返回void。