i have formated a string using sprintf() as follows:
int wValue = 1;
ostringstream ossi1;
ossi1 << "messageContent";
std::string orinal = "this is la large string \n
containin large content separated \n
by newline character"
char buff[50000] = {};
sprintf(buff, "What: %d @ Message: %s @ Detail: %s", wValue, ossi1.str().c_str(), orinal.c_str());
std::string myString(buff);
after some operation
im getting char* as follows:
char* varCharPointer = myString.c_str();
and i tried to separate that string using sscanf() as follows:
int varWhat;
char* strMesg = NULL;
char* strCall = NULL;
if(sscanf(varCharPointer, "What: %d @ Message: %s @ Detail: %s", &varWhat, strMesg, strCall) == 3)
{
// here tried to print the values of varWhat, strMesg and strCall but
// im aunable to print/get that value.
}
return value of sscanf() must be 3 but it gives 1. Anyone tell me what is the reason for above unexpected behaviour?
Thanks in advance.
scanf and it’s variants don’t work that way. For one, %s can only match strings with no spaces — so it’s certainly not going to work on orinal, and maybe not on ossi1 if “messageContent” is a stand-in for a string with spaces.
It’s best to use scanf for extremely simple parsing — e.g. “%d” to read an integer at the beginning, and almost never for strings, unless they absolutely cannot contain spaces.
Finally, you need to make strMesg and strCall buffers — scanf doesn’t allocate memory. I’m surprised it didn’t immediately crash.