注册 登录
编程论坛 C++教室

一个文件程序,里面有点小问题

lyj23 发布于 2011-05-07 15:19, 333 次点击
我用DEV C++
程序代码:
#include <fstream>
#include <conio.h>
#include <iostream>
using namespace std;

int main()
{
int a[10],max,i,order;
ofstream outfile("exercise_4.txt",ios::out|ios::trunc);
if(!outfile)
{

 cerr<<"can't open this file"<<endl<<"open error"<<endl;

 getchar();

 exit(0);
}
cout<<"put 10 number in this:"<<endl;
for(i=0;i<10;i++)

 {cin>>a[i];

 outfile<<a[i]<<" ";}
outfile.close();
//上半部分
ifstream infile("exercise_4.txt",ios::in);
if(!infile)
{

 cerr<<"can't open this file"<<endl<<"open error"<<endl;

 getchar();

 exit(0);
}
for(i=0;i<10;i++)
{

 infile>>a[i];

 cout<<a[i]<<" "<<endl;
}
cout<<endl;
max=a[0];
for(i=1;i<10;i++)

 if(a[i]>max)
  {
   max=a[i];
   order=i;
  }
cout<<"max="<<max<<endl;
cout<<"order="<<order<<endl;
getch();  //这里我写getch();就不会在执行完上半部分后闪屏而过,用getchar();为什么就会闪屏?
infile.close();   //这两个函数不是差不多吗,只不过显示和不显示。。
cout<<"The porgram is end."<<endl;
return 0;
}
5 回复
#2
qq10235692232011-05-07 15:29
我还真不懂!
#3
tisyang2011-05-07 17:45
程序代码:
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
  int a[10];
  cout << "Please input 10 interger: \n";
  for(int i=0; i<10; i++)
    {
      cin >> a[i];
    }
  
  ofstream outfile("exercise_4.txt", ios::out| ios::trunc);
  if(!outfile)
    {
      cerr << "Can't create file!\n";
      return 1;
    }

  for(int i=0; i<10; i++)
    {
      outfile << a[i] <<" ";
    }
  outfile.close();
  // this is the end of first part.
  
  ifstream infile("exercise_4.txt", ios::in);
  if(!infile)
    {
      cerr << "Can't open file!\n";
      return 1;
    }
  int b[10];
  for(int i=0; i<10; i++)
    {
      infile >> b[i];
    }
  infile.close();

  int max=b[0];
  int index = -1;
  for(int i=1; i<10; i++)
    if(b[i] > max)
      {
        max = b[i];
        index = i;
      }
  cout << "max= "<< max << endl;
  cout << "index= "<< index+1 << endl;
  cout << "This program ends." << endl;
  return 0;
}

大意应该是一样的。
for(i=0;i<10;i++)
{cin>>a[i];
outfile<<a[i]<<" ";}
这样的块既做输入,又做输出功能,最好不要有这样的写法。
#4
玩出来的代码2011-05-07 20:21
getchar
This is a standard function that gets a character from the stdin.
getche
This is a nonstandard function that gets a character from the keyboard, echoes to screen.
你说的闪屏是什么、是指等待输入吗。
#5
lyj232011-05-08 08:28
我说的闪屏就是DEVC++程序结束后没有看的时间!
直接一闪就没了!
写getchar()||getch()是为了等待键入字符!
为什么有时候getchar()写了照样闪,getch()就不闪了?
#6
玩出来的代码2011-05-08 11:28
看4L的解释,另有一个函数你可能会有用,fflush()/、最后一个回车符还残留在输入缓冲区中。
1