Thread: problems with strncpy

  1. #1
    Registered User
    Join Date
    Jul 2005
    Posts
    8

    problems with strncpy

    Hello, I'm trying to write a simple code that gets the word "apples" from the line "apples taste good", I tried using the source below but the source variable ended up returning something like this:
    source = apples╠╠╠╠+
    as you can see it has that weird ascii at the end.
    Code:
    char source[10]
    strncpy(source,"apples taste good", 7);
    I am not sure if im using the correct approach for this type of deal, but I'd appreciate any help, thank you.

  2. #2
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Hi,

    When you try to output a c-style string, a '\0' is needed to signal the end of the string. When outputting a c-style string, you are essentially executing code like this:
    Code:
    int i = 0;
    while(source[i] != '\0')
    {
    	cout<<source[i];
    	i++;
    }
    You didn't copy a '\0' into source, and you didn't add a '\0', so when you output source, the junk characters that happened to be in memory for each index position in source are output, and then you go out of bounds past the end of the array and output those characters, and then at some point cout<< fails and output is halted.
    Last edited by 7stud; 07-25-2005 at 04:57 PM.

  3. #3
    Registered User
    Join Date
    Jul 2005
    Posts
    8
    hello, thank you for your quick reply, but im still confused here, do i add "\0" to the end of my source variable? how does this change anything? this is what i tried doing from what you said.

    Code:
    char source[10];
    
    strncpy(source,"apples taste good", 7);
    strcat(source,"\0");
    cout << source;
    The number of characters to be copied is set to 7 with the null-terminal, but it still displays the junk at the end.

    Regards

  4. #4
    Registered User
    Join Date
    Jul 2005
    Posts
    8
    I figured a way to do this and this is how its done.

    Code:
    s = "apples taste good";
    ss = s.substr(0,6);
    cout << ss << endl;
    the output is:

    apples

    Thank you all!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. why is strncpy segfaulting here?
    By Calef13 in forum C Programming
    Replies: 3
    Last Post: 12-29-2008, 03:27 PM
  2. No clue how to make a code to solve problems!
    By ctnzn in forum C Programming
    Replies: 8
    Last Post: 10-16-2008, 02:59 AM
  3. strncpy adavnced :P
    By Joke in forum C Programming
    Replies: 3
    Last Post: 07-14-2008, 11:14 AM
  4. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  5. contest problems on my site
    By DavidP in forum Contests Board
    Replies: 4
    Last Post: 01-10-2004, 09:19 PM