c++常见操作的模板
2024-09-07 04:38:58
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);
最新文章
- STM32F412应用开发笔记之一:初识NUCLEO-F412ZG
- vs 颜色设置
- JS生成某个范围的随机数(四种情况)
- eclipse cdt代码悬停窗口背景颜色设置(转载)
- Textbox像百度一下实现下拉显示 z
- oc-06-无参方法的调用
- 充分发挥 JavaScript 语言的优势
- Linux下文件及目录的一些操作(附递归遍历目录源码)
- FUDCon - FedoraProject
- JS禁用右键,禁用打印,防止另存为,IE浏览器识别(转载)
- WPF popup置顶
- vue学习笔记(四)——Vue实例以及生命周期
- Hessian探究(一)Hessian与springMVC结合
- jq实现多选反选
- 用tensorflow实现最简单的神经网络
- flask接收post提交的json数据并保存至数据库
- 第44节:Java当中的JVM
- CentOS 6 升级 curl
- 运行python文件时出错SyntaxError: Non-UTF-8 code starting with &#39;\xb5&#39; in file, but no encoding declared;
- codeforces590b//Chip &#39;n Dale Rescue Rangers//Codeforces Round #327 (Div. 1)