Reputation: 11
I'm trying to write a program to split a string into the first 3 characters, the next 3 characters, and then the last 3 characters for the specific string.
int main(int argc, char *argv[])
{
char str[9] = "AbcDefGhi";
char first[3], second[3], third[3];
int ret;
ret = sscanf(str, "%3s%3s%3s", first, second, third);
printf("# variables: %i\n", ret);
printf("1: %s\n", first);
printf("2: %s\n", second);
printf("3: %s\n", third);
printf("whoops");
return 0;
}
But when I run it, the output is
# variables: 3
1: AbcDefGhi
2: DefGhi
3: Ghi
whoops
And I want
# variables: 3
1: Abc
2: Def
3: Ghi
whoops
Any help is appreciated.
Upvotes: 1
Views: 560
Reputation: 14046
String input conversions store a terminating null byte ('\0') to mark the end of the input; the maximum field width does not include this terminator.
That is, the buffer to store the string needs to be at least one byte larger than the maximum field width to account for the NUL terminator. So increase the size of all your arrays to account for the NUL terminator.
char str[] = "AbcDefGhi";
char first[4], second[4], third[4];
Upvotes: 1
Reputation: 612
I'm not sure if you need to do it without any functions from libraries, but I have created a code that is doing exactly what you want. Let us know if it's to complicated for you.
#include <stdio.h>
#include <stdlib.h>
char *split(const char *str, size_t size){
static const char *p=NULL;
char *temp;
int i;
if(str != NULL) p=str;
if(p==NULL || *p=='\0') return NULL;
temp=(char*)malloc((size+1)*sizeof(char));
for(i=0;*p && i<size;++i){
temp[i]=*p++;
}
temp[i]='\0';
return temp;
}
int main(){
char *p = "AbcDefGhi";
char *temp[5];
int i,j;
for(i=0;NULL!=(p=split(p, 3));p=NULL)
temp[i++]=p;
for(j=0;j<i;++j){
printf("%d: %s\n",j, temp[j]);
free(temp[j]);
}
printf("whoops");
return 0;
}
Upvotes: 0