Nicholas Taylor
Nicholas Taylor

Reputation: 11

Splitting a string in ansi C

I'm trying to find a way to split a single string into two separate variables. Right now I have:

char buffer[1024];
char firstName[16];
char lastName[16];
fgets(buffer, 1024, stdin);
sscanf(buffer, "%s %s", firstName, lastName);

When I later print the data, the first name is fine, but the last name will be the first and last combined. For example, when I enter "Joe Bob", the first would print "Joe" and the second would print out "Joe Bob". I have tried a few other ways such as using strtok and even sscanf with an offset pointer, but I keep getting the same result. How would I go about having the last name only contain the second name? I am using ansi C. Any help would be greatly appreciated.

Upvotes: 0

Views: 1814

Answers (1)

Miguel Prz
Miguel Prz

Reputation: 13792

first, read the whole string:

char line[64];
scanf("%[^\t\n]", line);

second, split it with strok

char *firstName;
char *lastName;
char *search = " ";

firstName = strtok(line, search);
lastName = strtok(NULL, search);

UPDATE: as @Zack comments, it's safer other way to read the string:

#define BUFFER_SIZE 64
char line[BUFFER_SIZE];

if (fgets(line, BUFFER_SIZE, stdin) != NULL) {
   /* ... */
}

Upvotes: 1

Related Questions