hi

im asked to read data inputs from a text file in c.

my problem is i dont know to separate the values,

ex. may data contains these:

1.00:2.00:3.00

i would like to assign the values a = 1:00, b = 2.00, c =3.00.

how is it done?

thanks!

Dani AI

Generated

A few practical, safe ways to parse a line like 1.00:2.00:3.00, plus notes on pitfalls seen in this thread (, , , ).

If the number of fields is fixed and small, use a single formatted parse (no tokenizing required). This is simple and robust as long as the format is stable:

char line[256];
float a, b, c;
if (fgets(line, sizeof line, fp) != NULL) {
    if (sscanf(line, " %f : %f : %f", &a, &b, &c) == 3) {
        /* a, b, c ready to use */
    } else {
        /* handle malformed line */
    }
}

For an unknown count of numeric fields, parse token-by-token with strtod so you get precise numeric conversion and an end-pointer to detect exactly where parsing stopped:

char line[256];
char *p = line, *end;
double val;
double values[32];
int count = 0;

if (fgets(line, sizeof line, fp)) {
    while (1) {
        errno = 0;
        val = strtod(p, &end);
        if (end == p) break;       /* no conversion */
        if (errno == ERANGE) { /* overflow/underflow */ }
        values[count++] = val;
        p = end;
        if (*p == ':') ++p;       /* skip delimiter */
        else break;
    }
}

Practical cautions and tips

  • strtok modifies the buffer and uses internal state; prefer strtok_r (reentrant) or strtod for numeric parsing.
  • Always check return values (fopen, fgets, sscanf, strtod) and guard buffer sizes.
  • If you allocate a buffer, keep the original pointer (free only the original) and do not call memset with sizeof(ptr) — store the buffer size in a constant.
  • Handle empty tokens, trailing delimiters, and locale decimal separators if your input may vary.
    These approaches avoid the pointer-manipulation and double-free pitfalls that showed up earlier in this thread and give clearer error detection.

Recommended Answers

All 7 Replies

you have a couple options:

1. use strtok() in a loop to extract the individual strings and copy the text into another string array.

2. use a pointer and strchr() to locate each colon then copy the text into another string up to the pointer that was returned by strchr().

#include <stdio.h>
#include <string.h>
int main ()
{
  char num[] ="1.00:2.00:3.00";
  char *ch;
  char r[100];
  printf ("split \"%s\":\n",num);
  ch = strtok (num,":");
  while (ch != NULL)
  {
    i = 0;
    printf ("%s\n",ch);
    ch = &r[i];
    ch = strtok (NULL, ":");
    i ++;
  }
  return 0;
}

--> here is my strtok code, but it doesn't work.

how can i copy the values of the pointer ch into a char array r? thanks.

Use [search]strcpy[/search] to copy the contents of the string pointed by ch to another string.

hi

im asked to read data inputs from a text file in c.

my problem is i dont know to separate the values,

ex. may data contains these:

1.00:2.00:3.00

i would like to assign the values a = 1:00, b = 2.00, c =3.00.

how is it done?

thanks!

This is the code which u want...

/*******************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fpInputFilePtr;
float a[3];
char strTokan[] = {":"};
char *strLineInfo = (char*) calloc(256,1);
char *ptrStrLineInfo = strLineInfo;
int nTmpCnt=0;
fpInputFilePtr = fopen("E:\\Test Projects\\Input.txt","r");
while(fgets(strLineInfo,256,fpInputFilePtr))
{
      strLineInfo[strlen(strLineInfo)-1]='\0';
      while(strlen(strLineInfo)>1)
      {
              strtok(strLineInfo,strTokan);
              a[nTmpCnt]=atof(strLineInfo);
              strLineInfo += strlen(strLineInfo)+1;
      }
      strLineInfo = ptrStrLineInfo;
      memset(strLineInfo,'\0',sizeof(strLineInfo));
}
/******** Do your work here*****/

if(fpInputFilePtr)
{
  fclose(fpInputFilePtr);
  fpInputFilePtr=NULL;
}
if(strLineInfo)
{
free(strLineInfo);
strLineInfo=NULL;
}
if(ptrStrLineInfo)
{
free(ptrStrLineInfo);
ptrStrLineInfo=NULL;
}
return 0;
}

/****************************/


If u have any queries feel free to mail to

Regards,
Jeganathan Krishnasamy.

Sorry, Jeg, but your code doesn't work either. The lines (16-21) using strtok() are incorrect and will only find the first occurence of the colon and no others. Please test out your program to make sure it works before attempting to show someone else how to write a program.

Definitely it'll work.Otherwise i won't put it here.I tested it and working fine.
plz once again check the code by running it or just debug it.I'm incrementing the character pointer.So each time i'm eliminating one ":".
This code is tested for 10 inputs from file.

here is how that loop should have been coded. Your program has a lot of unnecessary and just plain clumbsy code, such as the way it increments strLineInfo

while(fgets(strLineInfo,256,fpInputFilePtr))
{
      if( strLineInfo[strlen(strLineInfo)-1] == '\n')
                 strLineInfo[strlen(strLineInfo)-1]='\0';
      ptrStrLineInfo = strtok(strLineInfo,strToken);
      while(ptrStrLineInfo != NULL)
      {
              a[nTmpCnt]=atof(ptrStrLineInfo);
              ++nTmpCnt;
              ptrStrLineInfo = strtok(NULL, strTokan);
      }
}

>>memset(strLineInfo,'\0',sizeof(strLineInfo));
Since strLineInfo is a pointer the sizeof operator will always return the size of a pointer, which is 4 on most 32-bit compilers. So that memset line is pretty useless.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.