Search code examples
c++scanf

How do I use sscanf to split a string on a delimiter?


I want to get only 7b from 7b-7a with sscanf

I tried:

char str[32] = "7b-7a";
char out[32];
sscanf(str, "%s-%s", out);
std::cout << out;

Output is: 7b-7a

I need to output only 7b


Solution

  • In my opinion, the easier way would be to use streams and getline, like this.

    https://godbolt.org/z/4TTKz5KPx

    #include<iostream>
    #include<sstream>
    
    int main(){
        std::string in{"7b-7a"};
        std::stringstream ss{in};
    
        std::string out;
        std::getline(ss, out, '-');
        std::cout << out << "\n";
    
    }