3 Replies - 2156 Views - Last Post: 15 March 2012 - 11:46 PM Rate Topic: -----

#1 musya  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 11
  • View blog
  • Posts: 1,012
  • Joined: 25-April 07

c convert int to string

Posted 15 March 2012 - 10:37 PM

I'm trying to convert an integer (in this case my PID) to a char array.

I tried something like this:
char test = 4;
test = getpid();
	
printf("PID:%c", test);


But that only set the character to the assci representation of the the pid number.

Does anyone have any idea how to do this?

Thank you in advance
Is This A Good Question/Topic? 0
  • +

Replies To: c convert int to string

#2 aaa111  Icon User is offline

  • D.I.C Regular

Reputation: 88
  • View blog
  • Posts: 284
  • Joined: 21-February 07

Re: c convert int to string

Posted 15 March 2012 - 10:47 PM

Where is you character array.I can only see a char variable in whose you are assigning value 4 to it.
You can use itoa() or simply sprintf() to convert an integer to strings.sprintf is unsafe though,so the itoa() one is safe approach to do.See more of itoa:
http://www.cplusplus...y/cstdlib/itoa/

This post has been edited by aaa111: 15 March 2012 - 11:54 PM

Was This Post Helpful? 1
  • +
  • -

#3 sungchoiok  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 44
  • View blog
  • Posts: 140
  • Joined: 18-July 10

Re: c convert int to string

Posted 15 March 2012 - 11:10 PM

To convert from integer to string, (c-string to be exact), use "sprintf"

int sprintf ( char * str, const char * format, ... );

/* sprintf example */
#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;
}

Taken from sprintf - C++ Reference


But converting integer to string is not the problem you're having.
test = getpid();

variable test, you have declared as a character in line 1. getpid() does not return character, it returns pid_t which you can convert to integer by this: int test = (int)getpid();

Now, that you have a correct integer value of your pid, you simply printf it:
printf("PID:%i", test);


I suggest that you visit this link and see how the printf function works.

This post has been edited by sungchoiok: 15 March 2012 - 11:13 PM

Was This Post Helpful? 1
  • +
  • -

#4 musya  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 11
  • View blog
  • Posts: 1,012
  • Joined: 25-April 07

Re: c convert int to string

Posted 15 March 2012 - 11:46 PM

View Postaaa111, on 16 March 2012 - 05:47 AM, said:

Where is you character array.I can only see a char variable in whose you are assigning value 4 to it.
You can use snprintf or simply sprintf to convert an integer to strings.


Thanks sprintf did it!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1