Hi :).

I don't found good examples for function sscanf(). Can you help me please with this situation?

#include <cstdio>
#include <iostream>

using namepsace std;

int main(int argc, char const *argv[])
{

   string way = "main/articles/animals/giraffe";

   char arr[256]; char arr2[256];

   sscanf(way.c_str(), "%[^'/']/", arr);

   cout << arr << endl;

   return 0;

}

I need in one string "main" and in the second "articles/animals/giraffe".

How can I get the second part? And how can I use only "%" - without "%s" for string.

Is it possible have string instead of char arr[256]?

Thanks a lot :)!

Recommended Answers

All 2 Replies

If you have to do it using sscanf, you could do it like this:

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    string path = "main/articles/animals/giraffe";

    char * cPath1 = new char[path.size()];
    char * cPath2 = new char[path.size()];

    sscanf(path.c_str(), "%[^'/']/%[]", cPath1, cPath2);

    string path1(cPath1), path2(cPath2);

    delete[] cPath1; delete[] cPath2;

    cout << path1 << '\n' << path2 << endl;

    cin.get();
}

But why not do it the C++ way?

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string path = "main/articles/animals/giraffe";

    stringstream stream(path);
    string part1, part2;

    getline(stream, part1, '/');
    getline(stream, part2);

    cout << part1 << '\n' << part2 << endl;

    cin.get();
}

A couple of useful links -> sscanf, stringstream, getline

commented: Clearly and useful. +0

Thanks :). That's it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.