C++读取txt的随机行可以通过以下步骤实现:
完整的C++代码示例:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
string getRandomLine(const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
cout << "Failed to open file." << endl;
return "";
}
int lineCount = 0;
string line;
while (getline(file, line)) {
lineCount++;
}
srand(time(0));
int randomLine = rand() % lineCount + 1;
file.clear();
file.seekg(0, ios::beg);
int currentLine = 1;
while (getline(file, line)) {
if (currentLine == randomLine) {
file.close();
return line;
}
currentLine++;
}
file.close();
return "";
}
int main() {
string filename = "example.txt";
string randomLine = getRandomLine(filename);
if (randomLine.empty()) {
cout << "Failed to get random line." << endl;
} else {
cout << "Random line: " << randomLine << endl;
}
return 0;
}
这段代码将随机读取指定txt文件中的一行,并将其输出到控制台。你可以根据实际需求进行进一步的处理,如将随机行保存到变量、写入到另一个文件等。
推荐的腾讯云相关产品:腾讯云对象存储 COS(Cloud Object Storage),用于存储和管理海量的非结构化数据。产品介绍链接地址:https://cloud.tencent.com/product/cos
领取专属 10元无门槛券
手把手带您无忧上云