C++编写程序:
1.采用windows api;
2.创建结构体
struct Object {
double o_x, o_y; // 中心坐标
double o_width, o_height; // 长宽
};
3.创建上述结构体类型的数组;
4.读取.\Aaron_Eckhart文件夹下的txt文件,将文件中的字符按行处理:
如:1.37.jpg,165,142,61,61
每行的第一的逗号后到第二个逗号间的字符转成double传进o_x变量,
第二个逗号到第三个逗号间的字符转成double传进o_y变量,
第三个逗号到第四个逗号间的字符转成double传进o_width变量,
第四个逗号后的字符转成double传进o_height变量
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <windows.h>
struct Object {
double o_x, o_y; // 中心坐标
double o_width, o_height; // 长宽
double name;
};
std::vector<Object> ReadObjectsFromTxt(const std::wstring& filePath)
{
std::wifstream inputFile(filePath);
if (!inputFile)
{
std::wcerr << L"Failed to open input file: " << filePath << std::endl;
return {};
}
std::vector<Object> objects;
std::wstring line;
while (std::getline(inputFile, line))
{
Object obj;
std::wstringstream ss(line);
std::wstring token;
// Parse the line using comma as the delimiter
std::getline(ss, token, L',');
double name = std::stod(token.substr(token.find(L',') + 1));
std::getline(ss, token, L',');
obj.o_x = std::stod(token.substr(token.find(L',') + 1));
std::getline(ss, token, L',');
obj.o_y = std::stod(token.substr(token.find(L',') + 1));
std::getline(ss, token, L',');
obj.o_width = std::stod(token.substr(token.find(L',') + 1));
std::getline(ss, token, L',');
obj.o_height = std::stod(token.substr(token.find(L',') + 1));
objects.push_back(obj);
}
inputFile.close();
return objects;
}
int main()
{
std::wstring directory = L".\\Aaron_Eckhart";
std::wstring searchPath = directory + L"\\*.txt";
WIN32_FIND_DATAW fileData;
HANDLE hFind = FindFirstFileW(searchPath.c_str(), &fileData);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
std::wstring filePath = directory + L"\\" + fileData.cFileName;
std::vector<Object> objects = ReadObjectsFromTxt(filePath);
// Process the objects
for (const auto& obj : objects)
{
// Do something with the object data
std::cout << "Object: x=" << obj.o_x << ", y=" << obj.o_y
<< ", width=" << obj.o_width << ", height=" << obj.o_height << std::endl;
}
} while (FindNextFileW(hFind, &fileData) != 0);
FindClose(hFind);
}
return 0;
}
其中, double name = std::stod(token.substr(token.find(L',') + 1));
是为了去掉第一个逗号前的字符,为了更方便读取坐标;