turning variables into strings

This is a discussion on turning variables into strings within the C++ Programming forums, part of the General Programming Boards category; how can I turn a numeric variable (es. :INT number) into a string variable (char string)? I need to to ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    Code:
    char buff[30];
    sprintf( buff, "%d", myint );
    int nchars = strlen( buff );
    Like this?

  3. #3
    31173 h4x0r gnu-ehacks's Avatar
    Join Date
    Nov 2001
    Posts
    556
    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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    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, 10:34 AM
  3. Craps Program with Local Variables
    By tigrfire in forum C Programming
    Replies: 12
    Last Post: 11-09-2005, 08: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, 10:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21