learning C++ and going through some codes. I'm puzzled by how the following piece of code works. It's from the msdn library as part of an example, and I know that the code works, but I'm puzzled by how the "%" sign works.

#include "stdafx.h"
#include <stdio.h>

int main ()
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a %d char long string\n",buffer,n);
  return 0;

if someone can explain it to me, it'll be great

This is C style output. While legal in C++, usually cout or other output streams are used in C++. The % operator in this situation is a flag telling the compiler/linker that the following letter is a variable type and the letter stands for the variable type. d stands for int, s stands for string, c stands for char etc. The variable names to be used follow the statement in the double quotes with the first % refering to the first variable listed, the second % refering to second variable listed, etc. The number of % in the double quotes should match the number of variables listed after the double quotes.

I would not recommend using the microsoft website for any sort of help. It's pretty bad in general. This is one of the reasons why; they seem to have alot of strange and/or outdate (C language) snippets posted.

thanks, I've made some simple c++ programs, and this short little code snippet had me completely confounded (it's like, wat?, where did the "d" come from?).

I can see how that could be somewhat useful. Appreciate the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.