Hello every one.
I coded a program to seperate words from a file and want to input each seperated part to an array.But it doesnot work.Please help me!!
Here is the code

#include<stdio.h>
#include <string.h>
#define max 100
int main()
{ 
FILE *f;
char data[128];
char *p;
int host=0;
int i=0;
char ch[max]={0};
if((f=fopen("C:\data\def.txt","r"))==NULL){
printf("File cant open.....\n");
}
else{
while(fgets(data,sizeof(data),f)!=NULL){
host++;
p=strtok(data," | ");
for(i=0;i<3;i++){
ch[i]=p;
printf("%s\n",ch[i]);
} 
}
printf("Number of hosts:%d\n",host);
}
}

The text file looks like Host1 | Host2 | Host3 |
Thanks very much.Please help me!!!

How many times do you need to be told to use code tags? It's the third time I have asked you to do this.

The strtok() function has its pitfalls which have been well documented - do your own research on this.

Since this is more than likely an assignment on using strtok(), I will only help if:

1) you post your code again using code tags (AND YOU HAVE BEEN GIVEN THE LINK TO THE NOTES ON HOW TO DO THIS IN YOUR PREVIOUS POSTS!!!)

2) you research how to use the strtok() function correctly and change your code accordingly.

Other than that, from my perspective, you're on your own.

commented: good advice :) +36
fopen("C:\data\def.txt","r")

If you don't double it, the compiler is going to try to interpreted as the character \d which is wrong.

strtok() is a silly function with limited utility in reality.
It looks for the given characters and when it finds a first success, it changes as a NULL. Which means that the given string to search upon must be able to change. If the idea is to continue searching on the same string, guess what? There's no more string, because of the NULL, so you need to start from a NULL to make the remainder re-appear.
Perhaps you would be better served if you invest your time learning other ways of doing it. May I suggest Parsing a String into Tokens Using strcspn 1
By the way

ch[i]=p;
printf("%s\n",ch[i])

would never work because ch is a character and you are trying to assign a pointer to it, and then display it as a string.

i would also like u to read the strtok() manual first. If u are working in linux just type : man strtok
another thing is that u are trying to strore an array of string to an array of character. u have to declare the array to store the words

char* words[100];

u can now store address of 100 words in the "words" array.

hope that helps a bit...................good luck

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.