-
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.
-
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.
-
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
-
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!