Click here to Skip to main content
15,889,403 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
  char str[] = "bilal,1000,savings";
  char toFind; 
  char * word1;
  char * word2;
  char * word3;
  int i=0, numberOfFields = 3;
  static const char * listing[] = {"Name","Amount","Account"};
  char name[20], account[20];
  int amount;

  for(i=0; i<numberOfFields; i++){
    printf("%d. Here is your %s \n", i, listing[i]);
  }

  printf("Which one: ");
  scanf("%c", &toFind);

  if(toFind == '0'){
    printf("selected zero\n");
    word1 = strtok(str, ",");
    printf("%s\n", word1);
  }

  else if(toFind == '1'){
    printf("selected one\n");
  }

  else if(toFind == '2'){
    printf("selected two\n");
  }
  return 0;
}


What I have tried:

In this code, I want to select the second word from the file and the third one also and print that one but I am unable to fetch specific words. I searched a lot and done a lot of stuff to fetch the second and third words from the str variable but unable to do that?
Posted
Updated 31-Aug-20 20:11pm
v3

1 solution

After the initial call to strtok() you can pass NULL as the first parameter and strtok will use the previously supplied string buffer to return the next string.
word1 = strtok(str, ",");
word2 = strtok(NULL, ",");
word3 = strtok(NULL, ",");
if( toFind == '0') {
    printf("%s\n", word1);
}

or perhaps, more usually:
C
char *words[3];
i = 0;
for(word = strtok(str, ","); word != NULL; word = strtok(NULL, ",") {
    words[i++] = word;
}

int whichWord = atoi(toFind);
/* should check whichWord is in bounds here ... */

whichWord -= 1; /* user will have entered 1-3, but array runs 0-2 */
printf("%s\n", words[whichWord];

Note that if we need to increase the number of fields, all we need to do is to change char *words[3] to maybe char *words[10]. We could even dynamically allocate the variable words by counting the commas in the input string and then use a call to malloc() to create the needed space.

Be aware that strtok() modifies the input buffer, so you must not use a const char, as this will almost certainly cause a runtime error. Also, since the input buffer is modified, if you need to re-parse the input buffer, in this case, it will have all commas replaced with nul chars ('\0'). In that case, you might want to make a copy of the original input buffer, perhaps using strdup()
 
Share this answer
 
v2
Comments
CPallini 1-Sep-20 2:12am    
5.
KarstenK 1-Sep-20 3:20am    
Best is to create a working copy for strtok().
Maciej Los 1-Sep-20 17:18pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900