remove spaces from string
I have a little bug here. Can you let me know why I'm unable to print out or return the inputted string modified.
Code:
//ch11_9.c
//remove_spaces(char* given_string)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char* remove_spaces(char *given_string){
size_t line = strlen(given_string);
//create a buffer to hold the string
char* str_buf;
if( (str_buf = malloc(line +1)) == NULL){
perror("Unable to allocate storage for the string");
return NULL;
}
//iterate through the original string and the buffer...allocating all non whitespace to the buffer
while(*given_string && str_buf){
if(isspace(*given_string))
*str_buf = '-';
else
*str_buf = *given_string;
//end of either conditional so increment both
printf("%c", *str_buf);
given_string++;
str_buf++;
}
*str_buf='\0';
return str_buf;
}
int main(void){
puts("enter your line of text...empty line to quit");
char buffer[BUFSIZ];
fgets(buffer, BUFSIZ, stdin);
printf("\nnew string in main: %s\n", remove_spaces(buffer) );
return 0;
}