gpt4 book ai didi

c++ - 如何使用 C++ 检查 .text 文件中的字符序列?

转载 作者:太空狗 更新时间:2023-10-29 21:32:32 24 4
gpt4 key购买 nike

我有一个 .txt 文件,其中包含连续的字符序列(没有空格)。我想在 .txt 文件中搜索一系列字符,但在搜索时遇到了问题。

ifstream fin;
fin.open("sample.txt");
while (!fin.eof())
{
ch = getchar();
if (ch == 'p' && ch + 1 == 'o' && ch + 2 == 'w')
std::cout << "Sequence found" << "\n";
}
fin.close();

最佳答案

那不行,ch 是你读入的字符,但是 ch + 1 不是下一个字符(你还没有读入) ).它只是 ch 增加了 1,所以这是字母表中的下一个字母,数字更大,等等。取决于 ch 是什么.

如果您只是想查看一个序列是否在文件中,那么我会将文件读入一个std::string,例如this answer。说:

std::string slurp(std::ifstream& in) {
std::stringstream sstr;
sstr << in.rdbuf();
return sstr.str();
}

因此,您将 fin 传递给该函数,您将获得一个包含文件内容的字符串。然后你试着找到你的序列,比如 this answer解释:

if (myString.find("pow") != std::string::npos) {
std::cout << "found!" << '\n';
}

关于c++ - 如何使用 C++ 检查 .text 文件中的字符序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54822177/

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