putting integer in string

This is a discussion on putting integer in string within the C Programming forums, part of the General Programming Boards category; How can I put an integer value in a string? something like: Code: int a=5; char string[]=a; printf("\n%s\n",string); I tried ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    110

    putting integer in string

    How can I put an integer value in a string? something like:

    Code:
    int a=5;
    char string[]=a;
    printf("\n%s\n",string);
    I tried testing this out as part of a program, and after messing about a bit couldn't get it to work. Even though it compiled, when it ran, no string was printed.

    Also, if there is a way, can it be done for integers greater than 1 digit long also?
    Last edited by bertazoid; 10-28-2008 at 05:58 PM.

  2. #2
    Registered User
    Join Date
    Jan 2008
    Posts
    182
    Quote Originally Posted by bertazoid View Post
    How can I put an integer value in a string? something like:

    Code:
    int a=5;
    char string[]=a;
    printf("\n%s\n",string);
    I tried testing this out as part of a program, and after messing about a bit couldn't get it to work. Even though it compiled, when it ran, no string was printed.
    try this:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
        int a = 5;
        char string[32] = "This is my string.";
        
        sprintf(string, "%s %d", string, a);
        printf("%s", string);
        
        return 0;
    }
    Last edited by samus250; 10-28-2008 at 06:03 PM. Reason: typo

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Code:
    #include <stdio.h>
    
    int main () {
    	int a=97;
    	char string=a;
    	printf("&#37;c\n",string);
    }
    You can give an element of a string an integer value.
    Last edited by MK27; 10-28-2008 at 07:06 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,659
    > sprintf(string, "&#37;s %d", string, a);
    Right idea, but the result should go into a separate string.

    Very few functions are guaranteed to do the right thing when you're modifying the thing you're reading from.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User
    Join Date
    Oct 2008
    Posts
    110
    Thanks for the replies, I tried:

    Code:
    int main (void) {
    
    int a=24;
    int b=3;
    
    char string[32]="x^ ";
    
    sprintf(string,"&#37;d%s%d",a,string,b);
    printf("%s\n",string);
    
    
    return 0;
    }
    And it returned "24 24 3". Why does it print 'a,a,b', rather than 'a,string,b'?

    just noticed the new string part. I will try that out.

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    As Salem points out in post #4: You probably do not want to READ from and WRITE to the same string - you never know what sprintf() does to the input string - it almost certainly doesn't copy it before starting to write to the output string.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Registered User
    Join Date
    Oct 2008
    Posts
    110
    Quote Originally Posted by matsp View Post
    As Salem points out in post #4: You probably do not want to READ from and WRITE to the same string - you never know what sprintf() does to the input string - it almost certainly doesn't copy it before starting to write to the output string.

    --
    Mats
    Yeh thanks, I missed that when I made my post, and I tried it and it worked. hoorah!

    I have a new question, I'm using sprintf sucessfully now, and for what I want to do, the first thing I'm writing to the string is a char e.g:

    Code:
    sprintf(string,"&#37;c blahblah",char1);
    The problem is, this char is declared in a nested if statement, and only in one of the three cases do I want to actually have anything in there. for the other three cases, I want this to be ignored. I tried declaring the char only on this one case, and when the other two cases happened I got a hexagon with a question mark printed, indicating that I'm trying to print a char that hasn't been declared (It did compile).

    I also tried using

    Code:
    char char1=''; //nothing entered
    
    and
    
    char char1=' '; //with space
    but the first didn't compile, and the problem with the second is tha I don't want a space...just nothing at all. Is there something else I can use, between the single quotes?..I'd really like to do this without having to add more if/select statements (if possible).


    edit: Hmmm, can I use the null character, '\0'?
    Last edited by bertazoid; 10-29-2008 at 05:28 PM.

  8. #8
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Quote Originally Posted by bertazoid View Post
    Thanks for the replies, I tried:

    Code:
    int main (void) {
     
    int a=24;
    int b=3;
     
    char string[32]="x^ ";
     
    sprintf(string,"%d%s%d",a,string,b);
    printf("%s\n",string);
     
     
    return 0;
    }
    And it returned "24 24 3". Why does it print 'a,a,b', rather than 'a,string,b'?

    just noticed the new string part. I will try that out.
    That seems like very dubious code. if you always want "x^ " printed within the string why not just put "%dx^ %d" instead of trying to pass a string into itself... which will really not do what you are wanting at all.

  9. #9
    Registered User
    Join Date
    Oct 2008
    Posts
    110
    Quote Originally Posted by master5001 View Post
    That seems like very dubious code. if you always want "x^ " printed within the string why not just put "%dx^ %d" instead of trying to pass a string into itself... which will really not do what you are wanting at all.
    Yeh, I changed that already, after realising the same thing.

  10. #10
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Snap! Its more satisfying to notice that on your own, I am willing to bet Keep up the good coding, friend.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by bertazoid View Post
    Yeh thanks, I missed that when I made my post, and I tried it and it worked. hoorah!

    I have a new question, I'm using sprintf sucessfully now, and for what I want to do, the first thing I'm writing to the string is a char e.g:

    Code:
    sprintf(string,"%c blahblah",char1);
    The problem is, this char is declared in a nested if statement, and only in one of the three cases do I want to actually have anything in there. for the other three cases, I want this to be ignored. I tried declaring the char only on this one case, and when the other two cases happened I got a hexagon with a question mark printed, indicating that I'm trying to print a char that hasn't been declared (It did compile).
    There are a few ways to solve this problem. Simplest is to set it to '\0' and then check if it's '\0' - in that case, don't print it [putting a '\0' there will make string zero-length, becasuse sprintf isn't clever enough to know that you don't want a '\0' at the beginning of the string and thus make it an empty string].

    The second option is to use a char array instead of a single char. An empty string "" will print as "nothing" in sprintf.

    The third option is to use different format strings - only put the %c in the format string if it's actually needed - otherwise it will be ignored. Just beware that this ONLY works when it's the last argument(s) of sprintf that you want to skip, there is no way to skip argument 2, but print args 1, 3 and 4. You just have to use different printfs to do that.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    Registered User
    Join Date
    Oct 2008
    Posts
    110
    Quote Originally Posted by master5001 View Post
    Snap! Its more satisfying to notice that on your own, I am willing to bet Keep up the good coding, friend.
    Thanks. I always find myself writing a program, then getting tired and frustrated, missing stupid errors, soI go back to it with a fresh mind, solve the problem, and then just wanna keep adding and adding more and more to my program, and the cycle begins again.

    BTW, my program is making realy good progress (In large part due to the excellent helpers here!) and I almost have it finished. When I do, I want to make a GUI for it, and post it on my website, so I'll keep y'all posted.

    There are a few ways to solve this problem. Simplest is to set it to '\0' and then check if it's '\0' - in that case, don't print it [putting a '\0' there will make string zero-length, becasuse sprintf isn't clever enough to know that you don't want a '\0' at the beginning of the string and thus make it an empty string].

    The second option is to use a char array instead of a single char. An empty string "" will print as "nothing" in sprintf.

    The third option is to use different format strings - only put the %c in the format string if it's actually needed - otherwise it will be ignored. Just beware that this ONLY works when it's the last argument(s) of sprintf that you want to skip, there is no way to skip argument 2, but print args 1, 3 and 4. You just have to use different printfs to do that.

    --
    Mats
    Thanks, number two sounds like the best option for me, in fact this is exactly what I want, cheers.

  13. #13
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Quote Originally Posted by bertazoid View Post
    Thanks. I always find myself writing a program, then getting tired and frustrated, missing stupid errors, soI go back to it with a fresh mind, solve the problem, and then just wanna keep adding and adding more and more to my program, and the cycle begins again.
    That is basically how the game is played my friend. They say absense makes the heart grow fonder. When it comes to programming it makes the brain grow more observant and objective.

  14. #14
    Registered User
    Join Date
    Oct 2008
    Posts
    110
    very true

    matsp: I tried using a string instead of a char within my switch statement, but couldn't get it to work. When I declared it outside the switch statement, and then initialized it within, I got the compiler error: "Incompatible types in assignment." When I tried to declare the string within the statement, I got the compiler error "String undeclared..." (pointing meto the line wheren I'm trying to print it. I tried testing this idea in a program of its own, within an if statement, and got the same results. Here's the two codes I used respectively:

    Code:
    #include <stdio.h>
    
    int main () {
    
    int n=1;
    if(n==1){
      char string[]="+";
    }
    else{
      char string[]="";
    }
    
    printf("%s", string);
    
    return 0;
    }
    Code:
    #include <stdio.h>
    
    int main () {
    
    int n=1;
    char string[5];
    
    if(n==1){
      string="+";
    }
    else{
      string="";
    }
    
    printf("%s", string);
    
    return 0;
    }
    I don't understand why this doesn't work, since declaring/initializing other variable types within if/select statements seems fine.

    Also I noticed with the original case, where I was declaring a char within the statement (On one of the three conditions), then used sprintf, I wasn't getting the hexagonal question mark at the front of the string, when I used this by itself in int main, but for some reason I do get it when I use it within a function of its own (with a string as an input parameter), and then call the fucntion in main....The function is of type int and returns 0, but it does apply this process to the input string - just wrongly so.

  15. #15
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Code:
    #include <stdio.h>
    
    int main () {
    
    int n=1;
    if(n==1){
      char string[]="+"; /* This variable will go away when the block ends */
    } /* poof! */
    else{
      char string[]=""; /* ditto */
    } /* poof! */
    
    printf("&#37;s", string);  /*what variable "string"? */
    
    return 0;
    }
    For the second, you can never (and by never, we mean never) assign anything to an array. Ever. Of any kind. You can initialize an array at declare time, but you can never assign to it. If you want something to be put into a char array, you can use strcpy.
    Last edited by tabstop; 10-30-2008 at 01:19 PM. Reason: pretty colors

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 02:40 AM
  3. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  4. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-26-2003, 11:03 PM
  5. Putting integer in a string
    By minesweeper in forum C++ Programming
    Replies: 2
    Last Post: 02-25-2003, 11:43 AM

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