![]() |
#2
yyblackyy2010-04-07 11:37
#include <fstream>
#include<iostream> #include<cstdlib> using namespace std; //放到上面来,规范一些 int main( ) { ifstream in_stream; ofstream out_stream; int first=0, second=0, third=0; //初始化一下,防止意外情况 in_stream.open("infile.you"); if(in_stream.fail()) //判断是否打开成功 { in_stream.close(); //如果失败 in_stream.clear(); exit(-1); } else in_stream >> first >> second >> third; //获取你要的值 in_stream.close( ); //关闭文件流 out_stream.open("outfile.you"); //打开文件流 out_stream << "The sum of the first 3\n" << "numbers in infile.you\n" // 操作。。。。。。。 << "is " << (first + second + third) << endl; out_stream.close(); //关闭流 system("pause"); return 0; } ![]() 1: file.you文件所放的地方 因该是工程目录下(在调试的时候)或 *.exe 的文件目录下(在 dos下),生成的文件在工程目录下或*.exe的文件目录下 2: 在默认的输出输入文件流模式下不能用一个输入文件流和一个输出文件流同时关联同一个文件,原因是输出文件流默认模式下会将存在的文件清除,然后重建一个文件,这样 你的输入文件流就没有意义了,因为文件内容没有了。 ![]() |
1
2
3
4

#include <fstream>
#include<iostream>
int main( )
{
using namespace std;
ifstream in_stream;
ofstream out_stream;
in_stream.open("infile.you");
out_stream.open("outfile.you");
int first, second, third;
in_stream >> first >> second >> third;
out_stream << "The sum of the first 3\n"
<< "numbers in infile.you\n"
<< "is " << (first + second + third)
<< endl;
in_stream.close( );
out_stream.close( );
system("pause");
return 0;
}
然后译出来的结果应该是6,为什么我译出来的是一堆数字????#include<iostream>
int main( )
{
using namespace std;
ifstream in_stream;
ofstream out_stream;
in_stream.open("infile.you");
out_stream.open("outfile.you");
int first, second, third;
in_stream >> first >> second >> third;
out_stream << "The sum of the first 3\n"
<< "numbers in infile.you\n"
<< "is " << (first + second + third)
<< endl;
in_stream.close( );
out_stream.close( );
system("pause");
return 0;
}
谢谢