Jump to content

how to convert a character string to numbers and vice versa

- - - - -

  • Please log in to reply
11 replies to this topic

#1
onus

onus

    Programmer

  • Members
  • PipPipPipPip
  • 115 posts
Some one had recently asked me this question which I was not able to answer.
If my program is having an input of a number how can I convert this number to a string and use this string in my program.

Similarly if I am given a string how can I convert it to number.

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
The most simple way I can think of is to use atoi. itoa is not portable so you can use sprintf.
#include <stdio.h>
#include <stdlib.h>

int main() {
    //string and integer
    char somestring[] = "120";
    int someint = 120;
    
    //atoi, or string -> integer
    printf("%d\n", atoi(somestring));
    
    //safely place decimal into string
    char str[10];
    snprintf(str, sizeof(someint), "%d", someint);
    
    printf("%s", str);
}

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
atol() works -- sometimes. Maybe yes, and maybe no. It gives no indication of any errors. strol() is a better choice because it will report errors back to your program.

In c++ you can use stringstream class to convert between int and strings -- either direction.
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#4
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
In C, atoi() converts a string to an integer. itoa() converts an integer to a string. They are included in stdlib.h. C++ uses the same functions, but it uses different headers (I don't know what they are).
Programming is a journey, not a destination.

#5
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY

DarkLordofthePenguins said:

In C, atoi() converts a string to an integer. itoa() converts an integer to a string. They are included in stdlib.h. C++ uses the same functions, but it uses different headers (I don't know what they are).

itoa() is NOT defined in ANSI-C and is NOT part of C++.

#6
mnirahd

mnirahd

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 330 posts
Hi,

In C, you could use sscanf, sprintf function for conversion.

From number to string


int Mynumber = 12345;

char MyString[33];


sprintf(MyString, "%d", Mynumber);



In order to convert string to a number


int Mynumber ;

char *MyString = "123455";


sscanf(MyString, "%d", &Mynumber);



I hope this helps

Munir

#7
onus

onus

    Programmer

  • Members
  • PipPipPipPip
  • 115 posts
If you are sitting in an interview and you are not allowed to use any of the standard library function then any of the above does not help.

#8
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
It still trivial. For string to numerics, ASCII is sequential so you would apply a simple subtraction to each character. For numeric to string you would apply a modulus operator to iteratively split the number value, and apply the same ASCII addition to turn it into a string.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#9
onus

onus

    Programmer

  • Members
  • PipPipPipPip
  • 115 posts
Can you show me some code to do so?I do not have any idea of what you are saying.

#10
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts

int atoi(char* string)

{

   int i;

   int result = 0;

   if( string == NULL)

       return 0;

   // skip leading white space

   while(*string &&  isspace(*string) )

      string++;

   // convert digits to binary up to the first non-digit character

   while( *string && isdigit(*string) )

   {

         result = result * 10 + *string - '0';

         string++;

   }

   return result;

}


This one uses recursion to convert from int to std::string

#include <iostream>

#include <string>

using namespace std;


void itos(int n, string& s)

{

    if( n > 0)

    {

        itos(n/10, s);

        int x = n % 10;

        s += x + '0';

    }


}


int main()

{

    int n;

    string s;

    for(;;)

    {

        cout << "Enter a number\n";

        cin >> n;

        if( n < 0) break;

        itos(n, s);

        cout << s << '\n';

        s = "";

    }

}


Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#11
onus

onus

    Programmer

  • Members
  • PipPipPipPip
  • 115 posts
I don't have to use atoi,itos and isspace library functions.

#12
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
See post #10 -- it doesn't use those functions.
Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users