I currently am trying to extract a substring within a bufferline. The goal is to parse the string by whitespace and symbols to compile later. The line I'm trying to parse is the first line of my file.
void append(char* s, char c)
{
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
int main(void){
char str[] = "program example(input, output);";
char *f = str;
char *b = str;
char token[10];
if(*f != '\0'){
while (*f != ' ')
{
append(token,*f);
f++;
}
f++;
printf("%s",token);
token[9] = '\0';
}
return 0;
}
Am I clearing the token string wrong? The code only returns:
program
but it should return
program
example(input,
output);
There are a few things fundamentally wrong with your code (possibility of buffer overflow in your append() function, etc). I have changed just enough to allow the code to produce the desired result, to my understanding.
int main(void){
char str[] = "program example(input, output);";
char *f = str;
char *token=(char *)malloc((strlen(str)+1)*sizeof(char));
char *b = token;
while(*f != '\0'){
while (*f && *f != ' ')
{
*b++=*f;
f++;
}
if(*f) f++;
*b=0;
b=token;
printf("%s\n",token);
}
free(token);
return 0;
}
$ ./a.out program example(input, output);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.