D
Dominique =?ISO-8859-1?Q?L=E9ger?=
Hello guys,
I'm kinda new to C, and I'm having a hard time with strings. What I'm trying
to do is a simple function that trims spaces & tabs at the beginning of a
given string. For example, I want this: " Hello World" to become this:
"Hello World". At first glance, my function seems to work, but returns some
strange values...
Here's my code (please pardon the mess):
#include <stdio.h>
#include <string.h>
int main(void){
char *trimbegin(char *text);
char *str = " Hello World!";
char *result = trimbegin(str);
printf("What the function returns: \"%s\"\n", result);
return 0;
}
char *trimbegin(char *text){
int i = 0, j = 0, ok = 0;
int size = strlen(text);
char buffer[size + 1];
char *ptr;
printf("Original text is: \"%s\"\n", text);
printf("That's %d characters long...\n", size);
printf("Now, our text buffer can contain %d characters\n", size +
1);
for (i = 0; i <= size; i++){
if (ok == 1){
buffer[j] = text;
j++;
}
else if (isspace(text) == 0 && ok == 0){
buffer[j] = text;
j++;
ok = 1;
}
}
printf("What the result is supposed to be: \"%s\"\n", buffer);
ptr = buffer;
return ptr;
}
And here's the output:
[dom@localhost C]$ ./a.out
Original text is: " Hello World!"
That's 14 characters long...
Now, our text buffer can contain 15 characters
What the result is supposed to be: "Hello World!"
What the function returns: "Hello World! @8@$÷ÿ¿¸öÿ¿PS@ý@Èöÿ¿"
Why does it return "Hello World! @8@$÷ÿ¿¸öÿ¿PS@ý@Èöÿ¿" and not "Hello
World!"?
Thanks for all your help!
-Dom
I'm kinda new to C, and I'm having a hard time with strings. What I'm trying
to do is a simple function that trims spaces & tabs at the beginning of a
given string. For example, I want this: " Hello World" to become this:
"Hello World". At first glance, my function seems to work, but returns some
strange values...
Here's my code (please pardon the mess):
#include <stdio.h>
#include <string.h>
int main(void){
char *trimbegin(char *text);
char *str = " Hello World!";
char *result = trimbegin(str);
printf("What the function returns: \"%s\"\n", result);
return 0;
}
char *trimbegin(char *text){
int i = 0, j = 0, ok = 0;
int size = strlen(text);
char buffer[size + 1];
char *ptr;
printf("Original text is: \"%s\"\n", text);
printf("That's %d characters long...\n", size);
printf("Now, our text buffer can contain %d characters\n", size +
1);
for (i = 0; i <= size; i++){
if (ok == 1){
buffer[j] = text;
j++;
}
else if (isspace(text) == 0 && ok == 0){
buffer[j] = text;
j++;
ok = 1;
}
}
printf("What the result is supposed to be: \"%s\"\n", buffer);
ptr = buffer;
return ptr;
}
And here's the output:
[dom@localhost C]$ ./a.out
Original text is: " Hello World!"
That's 14 characters long...
Now, our text buffer can contain 15 characters
What the result is supposed to be: "Hello World!"
What the function returns: "Hello World! @8@$÷ÿ¿¸öÿ¿PS@ý@Èöÿ¿"
Why does it return "Hello World! @8@$÷ÿ¿¸öÿ¿PS@ý@Èöÿ¿" and not "Hello
World!"?
Thanks for all your help!
-Dom