[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 499
  • Last Modified:

Tokenize in C

I used the following code to read a file but something is going wrong with the token number. Is anyone who know what is going wrong?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


int main(){
   
    FILE *fp;
    char line[50];
    char *token,*token1,*token2,*token3;
    fp=fopen("Infofile.txt","r");
   
   
    if (fp ==NULL)
       {printf("File not exist\n");}
   
   while (!feof(fp))
   {
    fgets(line,60,fp);
    //printf("%s",line);
    ///////////////////////////////////
    token = strtok(line,"\n");
    token1 = strtok(token," ");
   
    //token2 = strtok(line," ");
    //  token3 = strtok(NULL," ");
    printf("%s\n",token1);
    getchar();
    ///////////////////////////////////
    }
    return 0;}



the format of the file is : name 1 10
0
Tom3333
Asked:
Tom3333
  • 2
1 Solution
 
Infinity08Commented:
It would help if you explain what you see that makes you think something is going wrong ...
0
 
Tom3333Author Commented:
the problem is that present all the line each time instead of word by word.

For example if i have the line George 1 20 in the read file
This code showed all the line .

I would like to receive first the word George then the number 1 and then the number 20 before move to the second line.  



How to do this????
0
 
Tom3333Author Commented:
No response yet?
0
 
AJRDevCommented:
Hi,

This prints your lines token-by-token:

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>


int _tmain(int argc, _TCHAR* argv[])
{
    FILE *fp;
    char line[50];
    char *token,*token1,*token2,*token3;
    
    fp=fopen("Infofile.txt","r");
   
    if(fp ==NULL)
    {
       {printf("File not exist\n");}
    }

    while(!feof(fp))
    {
        fgets(line,60,fp);
        //printf("%s\n",line);

        token1 = strtok(line," ");
        token2 = strtok(NULL," ");
        token3 = strtok(NULL," ");

        printf("%s\n",token1);
        printf("%s\n",token2);
        printf("%s\n",token3);
    }

    getchar();
    return 0;
}

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now