Home > Blockchain >  Comparing "Hello 4" to input in C
Comparing "Hello 4" to input in C

Time:10-22

I'm trying to use something like strcmp to compare a command like "Hello 4" and keep the 4 as a variable

Something like this:

if(strcmp(c, "Hello %d") == 0){
    int num = %d;
}

CodePudding user response:

You're looking for sscanf, which uses the scanf-style percent encoders you're using and takes a string to parse as its argument (as well as pointers to store the successful parses into).

It returns the number of arguments successfully stored, or a negative number in the case of an EOF error. In your case, we'll consider it a successful parse if we successfully store the one argument. If we get a zero, that's a failed parse, and if we get a negative number, that's a premature EOF, so we want the result of sscanf to be greater than zero.

#include <cstdio>
#include <iostream>

int main() {
  const char* c = "Hello 100";
  int num;
  if (std::sscanf(c, "Hello %d", &num) > 0) {
    std::cout << "Success! " << num << std::endl;
  } else {
    std::cout << "Failure..." << std::endl;
  }
}

Note that in the else branch, the num variable won't be assigned, so it will have whatever value your code previously assigned to it (which, in the code sample I've shown here, is nothing at all, hence UB). So be careful not to reference that variable in the failure branch.

CodePudding user response:

Regular expressions are a way to solve this if you're using C and not simply compiling C with a C compiler.

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string foo = "hello 4";

    std::smatch matches;

    if (std::regex_match(foo, matches, std::regex("hello (\\d )"))) {
        std::cout << matches[1] << std::endl;
    }

    return 0;
}
  • Related