gpt4 book ai didi

C++在读取文件时在字符串开头添加回车符

转载 作者:行者123 更新时间:2023-11-27 23:35:17 24 4
gpt4 key购买 nike

我有两个问题:

1) 为什么我的代码在 selected_line 字符串的开头添加回车符?
2) 你认为我用来从文件中返回随机行的算法足够好并且不会导致任何问题吗?

示例文件是:

line
number one
#
line number two

我的代码:

int main()
{
srand(time(0));
ifstream read("myfile.dat");
string line;
string selected_line;
int nlines = 0;
while(getline(read, line, '#')) {
if((rand() % ++nlines) == 0)
selected_line = line;
}
// this is adding a \n at the beginning of the string
cout << selected_line << endl;
}

编辑: 好的,你们中的一些人的建议很有道理。该字符串可能被读取为“\nmys​​tring”。所以我想我现在的问题是,如何从字符串中删除第一个\n?

最佳答案

你可能想要的是这样的:

std::vector<std::string> allParagraphs;
std::string currentParagraph;

while (std::getline(read, line)) {
if (line == "#") { // modify this condition, if needed
// paragraph ended, store to vector
allParagraphs.push_back(currentParagraph);
currentParagraph = "";
else {
// paragraph continues...
if (!currentParagraph.empty()) {
currentParagraph += "\n";
}
currentParagraph += line;
}
}

// store the last paragraph, as well
// (in case it was not terminated by #)
if (!currentParagraph.empty()) {
allParagraphs.push_back(currentParagraph);
}

// this is not extremely random, but will get you started
size_t selectedIndex = rand() % allParagraphs.size();

std::string selectedParagraph = allParagraphs[selectedIndex];

为了更好的随机性,你可以选择这个:

size_t selectedIndex 
= rand() / (double) (RAND_MAX + 1) * allParagraphs.size();

这是因为 rand() 返回的最低有效位往往表现得不那么随机。

关于C++在读取文件时在字符串开头添加回车符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/846121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com