Thread: Appending char to C-Style string

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    14

    Appending char to C-Style string

    I need to append one character from C-style String X (not necessarily the first char) to C-Style String Y. I was thinking of doing it thusly (this is in a for loop):

    Code:
    strncat(X, Y[i], 1)
    where Y[i] is the char to copy. Two questions:

    1. Will this work?

    2. Is there a better way?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    If Y is a C-style string, then you should be passing &Y[i] which is a pointer to that location in the string, not a character value.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    14
    Oh yeah, good point.

  4. #4
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629
    it should be safe as long you don't go out of bounds....
    but if you intend to use a loop...I am not sure if there is a point in using strncat?
    lol i would've just assigned it..although that is also a function
    You ended that sentence with a preposition...Bastard!

  5. #5
    Registered User
    Join Date
    Nov 2010
    Posts
    14
    How would I do it without strncat? X += y[i] or something?

    I need to do it in a loop because it checks if each stage is valid. For instance, where Y = 802143735:

    Code:
    X=8
    valid? no
    X=80
    valid? no
    X=802
    valid? no
    X=8021
    valid? yes
    exit loop

  6. #6
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629
    your life would be easier if you use the std::string object..is X a string object? if it is
    can I ask what makes X valid? does it compare with some previous Y string?
    if so
    Code:
    while(X!=Y)
       X+=Y[i] ;
    although you can try

    Code:
    while(!X.compare(Y))
       X+=Y[i] ;
    you will have to check the return value of compare...sorry I can't remember

    or if you
    i think should solve it for you.
    You ended that sentence with a preposition...Bastard!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sending a simple email in C++?
    By Coukapecker in forum C++ Programming
    Replies: 6
    Last Post: 04-09-2010, 12:36 PM
  2. Unable to compare string with 'getter' returned string.
    By Swerve in forum C++ Programming
    Replies: 2
    Last Post: 10-30-2009, 05:56 PM
  3. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  4. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  5. Replies: 4
    Last Post: 03-03-2006, 02:11 AM