C++函数记录

1、字符串转数字

	int X2 = std::stoi(argv[3]);

2、int main(int argc, char* argv[])

argc记录参数个数;argv[0]是exe文件的路径,argv[1]开始是设定的参数。在调试中,不同参数间用空格隔开

3、记录运行时间

这个见程序计时功能_珞珈Lena的博客-CSDN博客_程序计时

4、判断路径文件是否存在

    #include //头文件

	ifstream ifile(file_path, ios::in);
	if (!ifile.is_open()) {
		cout << "data1.txt文件打开失败!" << endl;
	}

5、读取txt文件中的参数(一行一行读取)

	const char* file_path = argv[1];//txt文件地址
	ifstream ifile(file_path, ios::in);
	if (!ifile.is_open()) {
		cout << "data1.txt文件打开失败!" << endl;
	}
	//读取参数
	string file_path_name;
	string leftx, rightx;
	string bandnum, file_path_nameout;
	getline(ifile, file_path_name);//读取第一行参数
	getline(ifile, leftx);//读取第二行参数
	getline(ifile, rightx);
	getline(ifile, bandnum);
	getline(ifile, file_path_nameout);

6、从路径中分离文件名

int  pos = file_path_name.find_last_of('\\');
	string s(file_path_name.substr(pos + 1));

7、参数中的字符串转为数字

    int X1, X2,bandn;
	sscanf(leftx.c_str(), "%d", &X1);
	sscanf(rightx.c_str(), "%d", &X2);
	sscanf(bandnum.c_str(), "%d", &bandn);

8、路径解析类

struct FileInfo
{
	string path;    //路径
	string format;  //格式
	string name;    //文件名
	FileInfo(string strFilePath)
	{
		int nDotIndex, nLastIndex, nUnderLine1, nUnderLine2, nUnderLine3;
		nDotIndex = strFilePath.find_last_of(".");
		nLastIndex = strFilePath.find_last_of("/");
		if (nLastIndex == -1)
		{
			nLastIndex = strFilePath.find_last_of("\\");
		}
		nUnderLine1 = strFilePath.find("_", nLastIndex);
		nUnderLine2 = strFilePath.find("_", nUnderLine1 + 1);
		nUnderLine3 = strFilePath.find("_", nUnderLine2 + 1);

		path = strFilePath.substr(0, nLastIndex);
		name = strFilePath.substr(nLastIndex + 1, nDotIndex - nLastIndex - 1);
		format = strFilePath.substr(nDotIndex + 1);
	}
};

9、设置main函数默认参数

if (argc < 4)
	{
		method = 2;//默认参数
	}
	else
	{
	sscanf(argv[3], "%d", &method);//输入参数
	}

10、进度条实现

for (int i = 0; i < num; i++)
	{
		int clock = num;
		printf("\r处理中[%.2lf%%]:", i * 100.0 / (clock - 1));
		int show_num = i * 20 / clock;
		for (int j = 1; j <= show_num; j++)
		{
			std::cout << "█";
			Sleep(10);
		}
    }

11、遍历指定类型文件

#include "dirent.h"

int scanFiles(vector& fileList, string inputDirectory)
{
	//inputDirectory = inputDirectory.append("\\");

	DIR* p_dir;
	const char* str = inputDirectory.c_str();

	p_dir = opendir(str);
	if (p_dir == NULL)
	{
		cout << "[GeoPositionVerify] | Failed to Open :" << inputDirectory << endl;
	}

	struct dirent* p_dirent;

	while (p_dirent = readdir(p_dir))
	{
		string tmpFileName = p_dirent->d_name;
		if (tmpFileName == "." || tmpFileName == "..")
		{
			continue;
		}
		else
		{
			FileInfo fileinfo(tmpFileName);
			if (fileinfo.format == "tiff" || fileinfo.format == "tif")
			{
				fileList.push_back(tmpFileName);
			}
		}
	}
	closedir(p_dir);
	return fileList.size();
}

 此处需要windows下的#include "dirent.h"库。可在以下链接下载https://download.csdn.net/download/Zm1366172479/87066849?spm=1001.2014.3001.5503

你可能感兴趣的:(C++,c++,开发语言)