c++常见操作的模板

1.统计时间

#include<ctime>
clock_t startTime = clock();
code();
clock_t endTime = clock();
cout << endl<< "time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " s"<<endl;

2.读取文件

#include<iostream>
#include<fstream>
#include<cstdlib>
const int SIZE=60; 
int main()
{
    using namespace std;
    char filename[SIZE]="information.txt";
    ifstream inFile;
    inFile.open(filename);
    if(!inFile.is_open())
    {
        cout<<"Could not open the file"<<filename<<endl;
        cout<<"Program terminating.\n";
        exit(EXIT_FAILURE);
    }
    double value;                                                                    //1
    double sum=0.0;
    int count=0;
 
    inFile>>value;                                                                     //1
    while(inFile.good())
    {
        ++count;
        sum=sum+value;
        inFile>>value;
    }
    if(inFile.eof())
    cout<<"end of file reached.\n";
    else if(inFile.fail())
    cout<<"input terminated by data mismatch.\n";
    else
    cout<<"input terminated for unknown reason.\n";
    if(count==0)
    cout<<"NO DATA PROCESSED.\n";
    else{
        cout<<"items read:"<<count<<endl;
        cout<<"sum:"<<sum<<endl;
    }
    inFile.close();       
     return 0;
}

3.写入文件

#incluede<fstream>
ofstream outFile;
outFile.open("carinfa.txt");        //要放入的文件名
outFile<<...                        //放入的信息
.
.
.
outFile.close();                    //关闭文件

4.产生0~89之间的随机数

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
    double target;
    srand(time(0));
    for(int i=0;i<=20;i++)
    {
    target=rand()%90;
    cout<<target<<endl;
    }
    return 0;
}

6.传二维数组

int show(double* A,int row,int col)
{
    int i,j;
    double** B=new double*[col];
    for(i=0;i<row;i++)
    {
       B[i]=new double[col];
     }
    for(i=0;i<row;i++)
    {
        for(j=0;j<col;j++)
        {
           B[i][j]=*(A+i*col+j);
           cout<<B[i][j]<<"  ";
        }
        cout<<endl;
     }
     for(i=0;i<row;i++)
     {
        delete[] B[i];
     }
     delete[] B;
 }
//调用: show(A[0],4,7);

转载于:https://www.cnblogs.com/qujingtongxiao/p/9862380.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值