我有一个 .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/