0

I have a code like this

 #include "atlstr.h"

void DisplayMessage(CString pszFormat, ...)
{
    CString str;
    va_list argList;
    va_start(argList, pszFormat);
    str.Format(pszFormat, argList);
    va_end(argList);

    _tprintf(_T("%s"), str);
}

void main()
{           
    DisplayMessage("This should be right %.2f = 700.0", 700.0);

    //Stop to watch
    int i = 0;
    scanf_s("%d",i);
}

But what I got when I run the code is

This should be right 0.00 = 700.0

I read this article and I got

... Notice that testit expects its second parameter to be either an int or a char*. ...

How can I fix this? The function str.Format can do it right so I know there must be a way - I have read the source code of the Format function but I still don't know how to fix it. Thank for reading :)

Community
  • 1
  • 1
123iamking
  • 1,735
  • 2
  • 22
  • 44
  • 2
    You should use `scanf_s("%d", &i);` to read the value. See also [What should `main()` return in C and C++](http://stackoverflow.com/questions/204476/). – Jonathan Leffler Apr 02 '16 at 04:57

1 Answers1

3

You should use CString::FormatV instead - it accepts va_list as the second argument. Passing va_list to the CString::Format is a bad idea, because it creates another va_list with va_list inside.

It is common to implement two methods: one with variadic number of arguments and another with va_list.

awesoon
  • 26,766
  • 9
  • 62
  • 86