Thread: adding a number at the end of a char

  1. #1
    Registered User
    Join Date
    Jul 2022
    Posts
    78

    adding a number at the end of a char

    adding a number at the end of a char


    Code:
        char c111 [30] = "aa";
        char c222 [30] = "bb";
        int num1 = 10;
    
    
        strcat(c111," ");
        strcat(c111,c222);
    
    
        printf("%s",c111);
        printf("\n");
        printf("%d",num1);
    
    
        strcat(c111, num1);
        printf("%s",c111);
    specific code

    Code:
    strcat(c111, num1);
    Last edited by WaterSerpentM; 10-13-2023 at 09:34 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,675
    Use sprintf.
    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.

  3. #3
    Registered User
    Join Date
    Jul 2022
    Posts
    78
    Quote Originally Posted by Salem View Post
    Use sprintf.
    Code:
    sprintf(c111, num1);
    ?

  4. #4
    Registered User
    Join Date
    Apr 2021
    Posts
    148
    There are programming languages, like Python, where it doesn't matter so much what the "type" of a piece of data is. In those languages, you can concatenate numbers and text strings and it will "just work." Some of them might require you to convert the number to a string, doing something like str(num) before you paste it on the end, but that's about it.

    C is not one of those programming languages.

    In C, you absolutely have to worry about types. If two pieces of data are of different types, there's no way to get them together. So you have to convert one into the other. And in many cases, you have to do the conversion in some specific way.

    Consider your case: you want to append a number to a string. What do you want to do with the result? Do you even care about the result, or do you just want to "appear" to append a number to a string, perhaps by printing them side-by-side.

    If that is true, just print them side-by-side:
    Code:
    printf("%s%d\n", "abc", 123);
    On the other hand, maybe you need to make an identifier to name a text file. So you want to "have" a string that is the result of appending a numeric string to a non-numeric string. If so, the easy way to do it is as @Salem suggested: use sprintf to write characters into a buffer.

    Code:
    // log2(10) is somewhere between 3 and 4. So assume 3. 
    // 64 bits divided by 3 is 21-ish. Assume 21 is the max # of
    // output digits. Add 1 for "sanity".  Add 1 for trailing NUL.
    
    #define MAX_NUM_DIGITS 23
    
    char buffer[sizeof(c111) + MAX_NUM_DIGITS];
    
    sprintf(buffer, sizeof buffer, "%s%d", c111, num1);    // buffer should contain "aa10"
    Finally, maybe you need to have lots of these strings laying around. Maybe you're making database keys or something, and there will be millions of entries, maybe billions. You're very concerned about performance.

    First: don't. There are very few problems that you will encounter that need that kind of concern. Just use sprintf or snprintf along with maybe strdup if you want to save a copy.

    Second: you can use lower-level code to generate your string. Do your own int-to-string conversion. Welcome to C!

    Code:
    #define MAX_BUF_LEN (sizeof c111 + MAX_NUM_DIGITS)
    
    char *
    make_identifier(
            const char * prefix,
            int sequence_number)
    {
            char buf[MAX_BUF_LEN];
    
            size_t plen = strlen(prefix);
            if (plen + MAX_NUM_DIGITS >= sizeof buf)
                    FATAL_ERROR("prefix string too long for internal buffer: %s", prefix);
    
            // Convert number to string at the back end of the buffer, working backwards
            char * wip = buffer + sizeof buf - 1;
            *wip-- = 0;
    
            int sn = sequence_number;  // work with a temporary value so we can print the original if needed
            do {
                    *wip-- = '0' + (sn % 10);  // ASCII/UTF-8 digits are in order, starting at '0', up through '9'. For this.
                    sn /= 10;
            } while (sn != 0);
    
            // If you have a negative number, you'll get an identifier with a minus in the middle: "aa-12"
            if (sequence_number < 0)
                    *wip-- = '-';
    
            assert(wip >= buf + plen);  // Reminder: We checked this at the top of the function.
            strcpy(buf, prefix);
            memmove(buf + plen, wip + 1, buf + sizeof buf - wip);
            return strdup(buf);  // Make a "forever copy" the caller can save.
    }

  5. #5
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,126
    aghast:

    The OP does not understand the language at all. The OP will not begin to understand what you presented.

  6. #6
    Registered User
    Join Date
    Jul 2022
    Posts
    78
    deleted
    Last edited by WaterSerpentM; 10-15-2023 at 06:25 AM.

  7. #7
    Registered User
    Join Date
    Apr 2021
    Posts
    148
    Quote Originally Posted by rstanley View Post
    aghast:

    The OP does not understand the language at all. The OP will not begin to understand what you presented.
    The fact they don't understand it today has no bearing on whether they will understand it tomorrow. Plus, I got to practice writing some C, and become a tiny fraction of a percent better as a tutor and coder. Why else would I even be here?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Adding one to every digit of number
    By culater in forum C Programming
    Replies: 3
    Last Post: 06-04-2015, 06:36 AM
  2. Adding numbers to a random number
    By Euan_R in forum C++ Programming
    Replies: 5
    Last Post: 01-24-2012, 12:11 PM
  3. Replies: 6
    Last Post: 07-15-2008, 02:27 PM
  4. What's problem of adding two binary number?
    By Mathsniper in forum C Programming
    Replies: 1
    Last Post: 01-12-2007, 06:12 AM
  5. Adding .txt to a char
    By ErionD in forum C++ Programming
    Replies: 11
    Last Post: 02-22-2002, 04:01 PM

Tags for this Thread