0

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 :)!

Edited by OrangeTree

2
Contributors
2
Replies
4
Views
4 Years
Discussion Span
Last Post by OrangeTree
1

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

Edited by m4ster_r0shi

Votes + Comments
Clearly and useful.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.