Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

C string manpulation question

  • 06-10-2005 02:55PM
    #1
    Registered Users, Registered Users 2 Posts: 4,228 ✭✭✭


    After years away from it i find myself back doing some C programming :(

    Anywho, heres my problem

    I'm passing in a char * into a function that has a carrige return at the end of it. I need it without it for transmission as part of another string to a socket.

    I've tried the following:

    char text_out[1024];
    int str_length = -1;

    str_length = (strlen(text_in) -1);
    strncpy(text_out, text_in, str_length);
    it looks fine but when i receive it at the socket there is "\CC\CC\CC\CC\CC\" until the end of the text until the end of the char array.


Comments

  • Registered Users, Registered Users 2 Posts: 1,481 ✭✭✭satchmo


    C Strings are NULL-terminated, in other words the last byte of every string is a 0 to show that that's where the string ends. You're removing the last byte of the string, and so removing the terminator - the program won't know where the string ends.

    To remove the carriage return you'll want to remove the last byte and change the second last byte (the return) to 0.


  • Closed Accounts Posts: 3,357 ✭✭✭Beano


    You dont even need to remove the last byte, just do

    text_in[strlen(text_in) -1]=0


  • Registered Users, Registered Users 2 Posts: 1,481 ✭✭✭satchmo


    True - removing the last byte too is just me being anal.


  • Registered Users, Registered Users 2 Posts: 4,228 ✭✭✭Scruff


    Cheers lads and\or lassies!
    That did the trick. Had overlooked that that text_in was an array of chars as well. Ah C strings, they're marvelous :rolleyes:
    Thanks again.


Advertisement