Converting an integer to string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • geeta719
    New Member
    • Mar 2010
    • 10

    Converting an integer to string

    void main()
    {
    char ch[10]="";
    char c;
    int k=0,l,i;
    printf("Enter a number:");
    scanf("%d",&i);
    while(i!=0) //reversing a numbr
    { k=k*10+i%10;
    i=i/10;}

    while(k!=0) //converting a number to string
    { c=48+k%10;
    strcat(ch,&c);
    k=k/10;}
    printf("\n%s",c h);
    }

    its posing an error of abnormal termination and not getting output as expected!!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    That is because strcat expects a pointer to a C style string and not a pointer to a single character.

    Why not just printf using the %d format specifier and print the number directly.

    Using 48 to denote the character '0' is very poor. What happens if you compile this program on a platform that uses a character set where '0' doesn't have the value 48?

    And finally you reverse the string twice so if you get this program working it will output what was input.

    Comment

    • geeta719
      New Member
      • Mar 2010
      • 10

      #3
      actually i want to convert an input integer to string......sin ce we can concatenate at the back of first string ,therefore first i m reversing the string and den using caoncatenation

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        What is your purpose for this?

        It would be just as easy to accept a string as input and then check that all the characters were digits as it would be to accept an integer and convert it to a string since basically all input from the keyboard starts as a string anyway.

        There are plenty of functions that will convert a string to an integer and an integer to a string for you.

        Comment

        • holyzuou
          New Member
          • Jan 2010
          • 13

          #5
          printf("\n%s",c h);
          ch is an array

          Comment

          Working...