Thread: turning variables into strings

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    7

    turning variables into strings

    how can I turn a numeric variable (es. :INT number) into a string variable (char string)? I need to to this in order to find out how long that string is , with the strlen() function. It's a data formatting trouble with a console program that I am porting from qbasic-dos to linux as my first C++ exercise.
    thanks

    *mercy for the newbie* :-P

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    char buff[30];
    sprintf( buff, "%d", myint );
    int nchars = strlen( buff );
    Like this?

  3. #3
    Welcome to the board jagerhans!
    What will people say if they hear that I'm a Jesus freak?
    What will people do if they find that it's true?
    I don't really care if they label me a Jesus freak, there is no disguising the truth!

    Jesus Freak, D.C. Talk

    -gnu-ehacks

  4. #4
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    in c++ there is also stringstreams....
    Code:
    #include<iostream>
    #include<sstream>
    using namespace std;
    int main()
    {
    ostringstream out;
    char str1[]={"I have "};
    char str2[]={" apples"};
    int apples=10;
    out<<str1<<apples<<str2;
    cout<<"The string in out is :- "<<out.str();
    return 0;
    }
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The slightly more obscure way of calculating the length of an integer is
    len = log10(x) + 1;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Global Variables
    By Taka in forum C Programming
    Replies: 34
    Last Post: 11-02-2007, 03:25 AM
  2. Problems with strings as key in STL maps
    By all_names_taken in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 11:34 AM
  3. Craps Program with Local Variables
    By tigrfire in forum C Programming
    Replies: 12
    Last Post: 11-09-2005, 09:01 AM
  4. turning real (number) variables into stirngs
    By Rune Hunter in forum C++ Programming
    Replies: 13
    Last Post: 08-28-2005, 09:11 AM
  5. Variables TO Strings
    By Okiesmokie in forum C++ Programming
    Replies: 2
    Last Post: 03-06-2002, 11:06 PM