how convert and return a C format string to string?

heres the function:
1
2
3
4
5
6
7
8
9
10
11
string ToString ( const char * format, ... )
{
  char buffer[256];
  va_list args;
  va_start (args, format);
  vsprintf (buffer,format, args);

  va_end (args);
  string a =buffer;
  return a;
}


these function do the same of the sprintf() function. but instead we use a variable for add the result, i want to return the result.
what's wrong with my function?
when i use it:
1
2
string f;
            f=ToString("hello world");

gives me several errors:
"error: crosses initialization of 'std::string f'"
"error: jump to case label [-fpermissive]"

so what i'm doing wrong?
It has nothing to do with the code you provided. You should post code which is around that lines (there is switch somewhere) and point al llines error referring to.
i found the problem:
when i use the switch case, in window procedure,i wasn't using the '{}'. that can make the compiler crazy(the manual that i study don't use the '{}' inside of switch case.

1
2
3
4
5
6
7
 case WM_KEYDOWN:
        {
            string f=ToString("hello world %d",100);
            MessageBox(NULL,TEXT(f.c_str()),TEXT("hi"),MB_OK);
        }
        return 0;
//other case message 

let me ask 1 thing: the 'return 0;' is better inside or outside the '{}'?
Does not matter. I would place it inside.
Only reason you are using brackets here is to limit scope of your variable.
thanks for the tip.
if i don't use the brackers, i get, again, that errors messages.
so i learn more about compiler errors ;)
that errors don't explain correctly :(
is like '@' in functions names... normaly is for add the libraries.
thanks for all
Nope, in your case compiler error was correct and descriptive.
As switch is just safe goto, all restrictions imposed in goto is still here. And you jump over initialization of local variable in current scope.
thanks for saying that.. now i think i understand
Last edited on
thanks for all... thank you
Topic archived. No new replies allowed.