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

Time:01-02

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

CodePudding user response:

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";

}

CodePudding user response:

You can try sscanf like this:

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    char str[32] = "7b-7a";
    char out[32];
    sscanf(str, "%[a-z0-9]-%*s",out);
    std::cout << out;
    return 0;
}
  • Related