Thread: strncpy. Need help.

  1. #1
    Registered User
    Join Date
    Oct 2012
    Location
    Philippines
    Posts
    7

    strncpy. Need help.

    How can I get the "not to" string and removing the "To be or" and the last "be"? What should I do?


    Code:
    #include<stdio.h>
    #include<conio.h>
    #include<string.h>
    int main(void)
    {
      char str1[]= "To be or not to be";
    char str2[6];
    strncpy (str2,str1,5);
      str2[5]='\0';
      puts (str2);
    getch();
    return 0;
    }
    Last edited by wacky_jay; 10-06-2012 at 06:36 AM.

  2. #2
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    Your str2 array has enough space for 6 characters (or a string with length 5).
    You are copying 10 characters into it.
    Lucky you: your computer didn't explode

    Code:
    char str2[7]; /* just enough space for the string "not to" */
    strncpy(str2, "To be or not to be" + 9, 6);
    str2[6] = '\0';

  3. #3
    Registered User
    Join Date
    Oct 2012
    Location
    Philippines
    Posts
    7
    Sorry qny, I edited the code. hehe.

  4. #4
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    In my mind this seems much more easy (look at the comments)
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        char* str= "To be or not to be";
        char result[7];/*7 because of the null terminator*/
        int i;
    
        /*skip characters until you find n*/
        while(*str != 'n')
        {
            *str++;
        }
        /*copy the requested string*/
        for( i = 0 ; i < 6 ; i++)
        {
            result[i] = *str++;
        }
        /*do NOT forget the null terminator*/
        result[6] = '\0';
        printf("Result is %s \n",result);
        return 0;
    }
    I could have declared result as a pointer to and then allocate memory with malloc

  5. #5
    Registered User
    Join Date
    Oct 2012
    Location
    Philippines
    Posts
    7
    Thanks qny! I finally got it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strncpy problem.
    By fpsasm in forum C Programming
    Replies: 2
    Last Post: 06-15-2010, 02:47 PM
  2. strcpy and strncpy
    By roaan in forum C Programming
    Replies: 5
    Last Post: 07-26-2009, 08:04 PM
  3. Strncpy
    By Poincare in forum C Programming
    Replies: 2
    Last Post: 07-15-2009, 09:13 PM
  4. strncpy problem
    By -EquinoX- in forum C Programming
    Replies: 4
    Last Post: 10-18-2008, 09:10 PM
  5. strncpy
    By zmaker5 in forum C Programming
    Replies: 12
    Last Post: 07-28-2007, 04:15 AM