2017-01-02 105 views
0

我需要輸出一個單詞,我輸入它的數字..我不能如何給一個單詞指定一個數字。下面是我用打破的話我一句一個FUNC strtok(),然後是IM失去了.. 爲exmp: 「HHH JJJJ KKKKK LLLLLL」 我進入3它。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; 
} 
+5

不要使用'gets()'。這太危險了。 –

+0

顯示預期的輸入和輸出。 – BLUEPIXY

+1

創建一個單詞數組,即一個char []數組,每個項目將包含一個單詞。並且要注意索引,數組以0爲基礎,在人腦中更有可能以1爲基礎。 – StephaneM

回答

0

1)不應該使用gets。這就是爲什麼在這裏是fgets(str, sizeof str, stdin);

2)我輸入一個數一個字以前我開始標記化而行

3)主要的算法是這樣的:

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

我當n找到單詞時,循環n上升,當用戶輸入一個數字並且IF等於num時,它就會跳出一個循環並打印出來。

#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; 
    }