christian christian - 4 months ago 7
C Question

How to split a line of text at delimiters

Here is my code. This currently opens a text file and prints a certain line depending on user input. I would like now to separate said line at appearances of a chosen delimiter (such as a comma) so I can get separate pieces of information (for example, weight, height, eye color, Name, Age, etc.). How would I go about doing that?(Edit im trying to use text input to determine the line printed out and nada any help?)

#include<stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
const char delim[2] = ",";
char *token;
int j =0;
char hh[3];
FILE *ptr_file;
char buf[1000];
ptr_file =fopen("input.txt","r");
if (!ptr_file)
return 1;
char *pt[] = {
"H","He","Li","Be","B","C","N","O","F","Ne","Na"

};
printf("what element do you want\n");
scanf("%s", &hh);
for(j=0; j<= 3; j++)
{
if(hh == pt[j])
{
fgets(buf,1000, ptr_file);
token = strtok(buf, delim);
while( token != NULL )
{
printf( "%s\n", token );
token = strtok(NULL, delim);
}

break;
}else
{
fgets(buf,1000, ptr_file);
continue;
}
}
fclose(ptr_file);
return 0;
}

Answer

If you have your sentence: "Weight,Height,Eye color,Name,Age", you can tokenize the string and separate it by the comma (",") by using the

char *strtok(char *str, const char *delim) function as follows.

char buf[1000] = "Weight,Height,Eye color,Name,Age";
const char delim[2] = ",";
char *token;

//This retrieves the first token
token = strtok(buf, delim);

while( token != NULL ) 
{
  printf( "%s\n", token );
  token = strtok(NULL, delim);
}

Output:
Weight
Height
Eye color
Name
Age

Comments