output the right word

83 views Asked by At

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

There are 1 answers

0
Nikita Gusev On

1) should not use gets. That's why here is fgets(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.

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

    int main(void){
        char str[80], *p;
        const char *sp = " \n";
        int n = 0, num = 0;

        printf("Enter your line: ");
        fgets(str, sizeof str, stdin);
        printf("n: ");
        scanf("%d", &num);

        p = strtok(str, sp);
        while (p != NULL && n < num){
            if(++n == num){
                printf("%s\n", p);
                break;
            }
            p=strtok(NULL, sp);
        }

        return 0;
    }