none
How to print % inside s(w)printf()? RRS feed

  • Question

  • int main(void)
    {
    char msg[100];
    sprintf(msg,  "100%%\n");
    printf(msg);

    wchar_t msg1[100];
    swprintf(msg1, L"100%%\n");
    wprintf(msg1);

    }

    The above program had been working in the past now it has stopped? I am using C++ in Visual Studio 2017. Both the above prints just 100. What am I missing? Please enlighten. I tried various escape chars and quotes nothing worked. 

    thanks

    ananda


    Saturday, October 26, 2019 12:19 AM

Answers

  • The problem is that you are misusing printf here.  sprintf and swprintf are doing exactly what you expect; they are producing the string "100%\n".  You then pass that to printf, but you're passing it as the format string, where it is going to be interepretted again.  Printf now sees the single % and removes it.

    You should NEVER pass an arbitrary string as the first parameter to printf.  Either use puts or fputs, or do

        printf( "%s", msg );


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Saturday, October 26, 2019 12:26 AM

All replies

  • The problem is that you are misusing printf here.  sprintf and swprintf are doing exactly what you expect; they are producing the string "100%\n".  You then pass that to printf, but you're passing it as the format string, where it is going to be interepretted again.  Printf now sees the single % and removes it.

    You should NEVER pass an arbitrary string as the first parameter to printf.  Either use puts or fputs, or do

        printf( "%s", msg );


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Saturday, October 26, 2019 12:26 AM
  • Thank you. Yes when I say it was working the original code had fputs(). I never realized that. Thanks a lot. You made my weekend. 

    regards

    ananda

    Saturday, October 26, 2019 12:32 AM