i need to output a word, which i enter a number of it.. I can't how i should assign a number to a word. Here is i use a func strtok()
for breaking my sentence on words, then im lost..
for exmp: " hhh jjjj kkkkk llllll" i entered 3
it ouputs :kkkkk
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[80],*p;
char sp[20]=" ";
int i,n=0,num;
printf("Enter your line: ");
gets(str);
p=strtok(str,sp);
while (p!=NULL){
for(i=0;i<p;i++){
printf("%s - [%d]\n",p,i+1);
p=strtok(NULL,sp);
n=p;
}
n++;
}
printf("n: ");
scanf("%d",&num);
if(num==n){
printf("%s",p);
}
return 0;
}
1) should not use
gets
. That's why here isfgets(str, sizeof str, stdin);
2) i enter a number of a word BEFORE i start tokenizing the line
3) the main algorithm is in this :
while (p != NULL && n < num){ if(++n == num){ printf("%s\n", p); break; } p=strtok(NULL, sp); }
in my loop n rises while it finds word,when a user enters a number and IF it equally to num,so it breaks out of a loop and print it.