NO

Author Topic: Need sprintf to format an integer to text, but confused with fundamentals  (Read 3712 times)

EdPellesC99

  • Guest

   Hi,

   This code works
Code: [Select]
#include <stdio.h>

int main()
{
char buff[50];
int ret, a = 34;
ret = sprintf(buff, "%d",a);
printf ("\n\nbuf as text is: %s and the buffer has %d characters.\n\n",buff,ret);
return 0;
}

   Can someone explain to me why the following compiles, but does not run:

Code: [Select]
#include <stdio.h>

int main()
{
char buff[50];
int ret, a = 34;
ret = sprintf(buff, "%d",a);
printf ("\n\nbuf as text is: %s and the buffer has %d characters.\n\n",buff[0],ret);
return 0;
}

On a sidenote: I continue, hopefully not forever, to have problems with the concept of pointers.



Anyway, on the last code block, doesn't integer "a" get written to the first cell of buff as text?



  Thanks in advance for all help,
  ... Ed


Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Use &buff[0] for pointer to string
May the source be with you

EdPellesC99

  • Guest
   Great Timo,

   Thanks very much, I do not think I would ever have figured that one out. Sometimes you just get stuck, and you stay there no matter how many places you look for answers, and no matter how many times you try things in new ways.

  Very nice, I am stunned at the moment, and might ask a question in a day or two after my brain is capable.

  Tx much, Ed

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Example to use sprintf and array of char
Quote
#include <stdio.h>

int main(int argc, char **argv)
{
   int pos;
   char buff[100];

   pos = 0;
   for (int i=0; i<=10; i++) {
      pos += sprintf(&buff[pos], "i=%d\n", i);
   }
   printf(buff);
   return 0;
}

Tutorial for pointers:
http://home.netcom.com/~tjensen/ptr/pointers.htm
« Last Edit: July 06, 2010, 12:27:42 PM by timovjl »
May the source be with you

EdPellesC99

  • Guest
 
  Tx Timo,

  For the info, and the link. I will be reading, .......it looks like some great info.

  Tx again, and I like that color syntax in the post !  :) :)

.....Ed