need help for simple c++ programming

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • news.hku.hk

    need help for simple c++ programming



    As myfile.txt is the required filename, i try to extract the string
    "myfile.txt " to variable "filename" of type char from buffer
    i1: position of "m" in "myfile.txt "
    i2: position of the last "t" in "myfile.txt "
    buffer: a character array containing many words in
    *************** *************** *************** * while(i1 < i2) {
    strcat( filename, buffer[i1] );
    i1++;
    }; *************** *************** *************** ** The above
    lines generate error. I think this is because buffer[i1], buffer[i1+1],
    ...... are some characters without the ending '\0' and therefore cannot be
    used in the strcat function. But is there any ways to achieve my purpose? or
    i simply go to a completely wrong direction? Thanks for your kind attention.



  • Sean Kenwrick

    #2
    Re: need help for simple c++ programming


    "news.hku.h k" <billychu@hkusu a.hku.hk> wrote in message
    news:3fe434c3$1 @newsgate.hku.h k...[color=blue]
    >
    >
    > As myfile.txt is the required filename, i try to extract the string
    > "myfile.txt " to variable "filename" of type char from buffer
    > i1: position of "m" in "myfile.txt "
    > i2: position of the last "t" in "myfile.txt "
    > buffer: a character array containing many words in
    > *************** *************** *************** * while(i1 < i2) {
    > strcat( filename, buffer[i1] );
    > i1++;
    > }; *************** *************** *************** ** The above
    > lines generate error. I think this is because buffer[i1], buffer[i1+1],
    > ..... are some characters without the ending '\0' and therefore cannot be
    > used in the strcat function. But is there any ways to achieve my purpose?[/color]
    or[color=blue]
    > i simply go to a completely wrong direction? Thanks for your kind[/color]
    attention.[color=blue]
    >
    >[/color]
    buffer[i1] is a char NOT a null terminated string of chars. Remember that
    there is no difference between a char and an int (except that a char might
    be one or two bytes long instead of two or four bytes long (but you cannot
    rely on this)). To do what you are trying to do you could do the
    following:

    while(i1 < i2) {
    filename[i1]= buffer[i1] ; // Assign the array elements char
    by char
    i1++;
    };

    Or you could force buffer to be a NULL terminated string and use the string
    functions...

    buffer[i2]='\0'; // Null terminate the array of chars makeing a 'string'
    strcpy(filename ,buffer); // Now just use strcpy to copy into the filename
    array (null terminated)

    Sean



    Comment

    Working...