inpotk
inpotk

Reputation: 25

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

Upvotes: 1

Views: 127

Answers (2)

tejas
tejas

Reputation: 1925

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

}

Upvotes: 3

Filip Stojakovic
Filip Stojakovic

Reputation: 39

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

Upvotes: 2

Related Questions