来自作者的测试数据生成代码
2025-09-26 13:40:06
发布于:广东
21阅读
0回复
0点赞
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sys/stat.h>
#include <direct.h> // 增加Windows兼容性
using namespace std;
// 检查文件夹是否存在
bool folderExists(const string& path) {
struct stat info;
if (stat(path.c_str(), &info) != 0) {
return false; // 文件夹不存在
}
return (info.st_mode & S_IFDIR) != 0; // 检查是否为目录
}
// 创建文件夹
bool createFolder(const string& path) {
#ifdef _WIN32
// Windows系统创建文件夹
int result = _mkdir(path.c_str()); // 使用Windows专用的_mkdir函数
#else
// Linux/Mac系统创建文件夹
int result = mkdir(path.c_str(), 0755); // 使用更安全的权限设置
#endif
return result == 0;
}
int main() {
// 设置随机数种子
srand(time(0));
int M, N;
string folderName = "test_data"; // 固定文件夹名,无需用户输入
string fileName;
// 获取用户输入
cout << "请输入M(每个字符串长度)和N(字符串数量): ";
cin >> M >> N;
cout << "请输入要保存的文件名(例如:input1.txt): ";
cin >> fileName;
// 检查并创建文件夹
if (!folderExists(folderName)) {
cout << "尝试创建文件夹: " << folderName << endl;
if (!createFolder(folderName)) {
cerr << "错误:无法创建文件夹 '" << folderName << "'" << endl;
cerr << "可能的原因:权限不足或路径包含特殊字符" << endl;
return 1;
}
cout << "文件夹创建成功: " << folderName << endl;
} else {
cout << "文件夹已存在: " << folderName << endl;
}
// 构建完整文件路径
string fullPath;
#ifdef _WIN32
fullPath = folderName + "\\" + fileName; // Windows路径格式
#else
fullPath = folderName + "/" + fileName; // Linux/Mac路径格式
#endif
// 打开文件用于写入
ofstream outFile(fullPath.c_str());
if (!outFile) {
cerr << "错误:无法创建文件 '" << fullPath << "'" << endl;
return 1;
}
// 写入测试数据
outFile << M << " " << N << endl;
for (int i = 0; i < N; ++i) {
string s;
for (int j = 0; j < M; ++j) {
s += (rand() % 2 == 0) ? 'h' : 'b';
}
outFile << s << endl;
}
// 关闭文件并显示结果
outFile.close();
cout << "\n测试数据生成完成!" << endl;
cout << "文件保存路径:" << fullPath << endl;
#ifdef _WIN32
cout << "你可以在资源管理器中输入以下路径访问:" << endl;
cout << "\"" << fullPath << "\"" << endl;
#else
cout << "你可以在终端中输入以下命令访问:" << endl;
cout << "cd " << folderName << " && cat " << fileName << endl;
#endif
return 0;
}
全部评论 4
不要把这段代码复制拿来提交!!!
这只是我用来生成随机测试数据输入部分的代码,不是题目的正解!18小时前 来自 广东
0八嘎
2天前 来自 广东
0太赞了!
2天前 来自 广东
0哈哈
2天前 来自 广东
0
有帮助,赞一个