0

I take user input in char name[20] using fgets like this:

fgets(name,20,stdin);            

The user enters two strings separated by white space like John Smith. What if I wanted to use John and Smith in two strings like char name[20] , char surname[20] or just compare John and Smith using strcmp?

I tried a lot, but I did not find any way to do this.

What are some ways to fix this kind of problem?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
ranaarjun
  • 245
  • 3
  • 5
  • 12

3 Answers3

2

You need to learn char * strtok (char *restrict newstring, const char *restrict delimiters) function in C uses to splitting a string up into token separated by set of delimiters.

You input string John Smith is separated by space (' ') char. You need to write a code something like below:

char *token;
token = strtok(name, " ");  // first name 
strcpy(fname, token);
token = strtok(NULL, " ");  // second name 
strcpy(lname, token);
Grijesh Chauhan
  • 55,177
  • 19
  • 133
  • 197
0

You will need to search for the blank within the string yourself - look up the strchr function for that. Then, use strncpy to copy the two parts in 2 different strings.

Guntram Blohm
  • 9,349
  • 2
  • 22
  • 28
0

Use the strtok function to split strings.

egur
  • 7,605
  • 2
  • 26
  • 47