Hi all, I have a decent amount of knowledge of C++ and I'm working on creating a simple blockchain (not cryptocurrency, just blockchain) implementation in C++, I want to find a certain sequence of characters, in this case "000" in a string to check if a hash (stored as a string) is valid. However, I've tried using the member functions of std::string to do that, but it only looks to see if there is a 0 anywhere in the string, but I want it to look and see if a string has a sequence of characters. Any help on this issue would be appreciated! :D
Heres a code snippet of my current attempt at trying to do this:
1 2 3 4 5 6 7 8 9 10
std::string output; // pretend theres a sha256 hash here
if(output.find("000")) // Heres where it checks if there is 000 present
{
std::cout << "Hash is valid - Block confirmed" << std::endl;
validHash = true;
returntrue;
}
Having a decent knowledge of a programming language includes being able to look up how a function actually works instead of making assumptions about it. std::string::find doesn't return a bool. It returns a size_t (more specifically, a std::string::size_type) indicating where in the string the target was found. If the target is not found in the string, it returns std::string::npos (generally equal to size_t(-1), i.e., the highest size_t value). So you need to say:
Well, I did a return true statement as this is part of a class and the code snippet I provided is part of a boolean function, I apologize if im being ignorant and a little stupid about all this, this is my first time on this forum and I'm still learning the ins and outs of C++
If you want, I can provide the full class code I'm working with to give more insight into my issue
Nobody's saying you can't return true. You can return whatever you want from your own functions. The point is that std::string::find doesn't return a boolean, but you are using it as if it did. It returns a size_t (an unsigned integer type). You need to rewrite your code snippet like this:
1 2 3 4 5 6 7 8
std::string output; // pretend theres a sha256 hash here
if(output.find("000") != std::string::npos)
{
std::cout << "Hash is valid - Block confirmed" << std::endl;
validHash = true;
returntrue;
}