I’m inputting a string by using fgets, e.g. “Hello World”. I want to try and delete the white space inbetween the word, however what I am trying keeps returning hello@world (where @ is a random character).
void sortString(char phrase[])
{
int i, j;
char temp[200];
for(i = 0; i < 200; i++)
{
if(!(isspace(phrase[i])))
{
temp[i] = phrase[i];
}
}
printf("%s", temp);
}
So i’m basically copying the character[i] over from the phrase to a temp array if it isn’t a whitespace, but i’m unsure as to why i’m getting a random character instead of just, for example, helloworld.
Whenever you see a whitespace character in
phrase, you are simply skipping over the equivalent location intemp, leaving it uninitialized (containing garbage). You need a separate counter to keep track of the current location in thetemparray.Also, you should check for the string in
phraseterminating with a\0character, rather than blindly copying all 200 characters, and make sure thetempstring is safely terminated too.Making sure
temp[]is actually big enough for the resulting output is left as a further exercise. (Look in Gandaro’s answer for a clue.)