Question

I was wondering if there was a less....listy way to do this? I have an assignment that puts credit card information in a UDP packet, with the information separated in the buffer by colons, so that it looks like Bob Jones:7845 6133 7889 4425:09/2017:654.99 stored in a single character array.

int main(int argc, char **argv)
{
    char buffer[256];
    char name[64];
    char cardNum[32];
    char expiration[8];
    char amount[14];

    while(true)
    {
        /*********
        (Input prompts go here, break if user types quit)
        *********/

        strcpy(buffer, amount);
        int length = strlen(buffer);
        buffer[length] = ':';
        strcat(buffer, cardNum);
        length = strlen(buffer);
        buffer[length] = ':';
        strcat(buffer, name);
        length = strlen(buffer);
        buffer[length] = ':';
        strcat(buffer, expiration);

        /***************
        (run all of the networking code)
        ***************/
    }

    return 0;
}
Was it helpful?

Solution

In C++, you can concatenate std::string objects using +, or append to a string stream.

In both C and C++ you have access to formatted output, which I think is preferred here, because the whole code fits neatly on a single line:

sprintf(buffer, "%s:%s:%s:%s", amount, cardNum, name, expiration);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top