与えられた複数の文字列を辞書順でしてある範囲の単語を表示させるプログラムを作っているのですが
strcpy()を使用している個所から挙動がおかしくなってしまいます。
入力として、与えられるのは
(総単語数:n) (1ページあたりの単語数:k) (何ページ目か:p)
(単語:s[0]) (単語:s[1]) ...
で、
<例>
7 3 2
dog cat bird cow bear rabbit mouse
上記のように与えられます。
上の例の場合ソートした結果、
bear bird cat cow dog mouse rabbit
となるので、
出力は
cow dog mouse
となるのが理想です。
s[0],s1だけソートした結果、
cat
dog
bird
cow
bear
rabbit
mouse
と正常に処理しますが、
s[0],s2だけソートした結果、
bird
dog
cow
bear
rabbit
mouse
となってしまいます、、、
s[1]が消えてしまう原因は何なのでしょうか?
原因が分かる方、ご教授願います。
c
1 2#include <stdio.h> 3#include <string.h> 4#include <stdlib.h> 5 6int main(void){ 7 8 char str[100], *ch, *s[1000], tmp[]="unkooooooo"; 9 int n=0, k=0, p=0, i=0, j=0, min=0; 10 //入力の処理 11 fgets(str, sizeof(str), stdin); 12 ch = strtok(str, " \n"); 13 n = atoi(ch); 14 ch = strtok(NULL, " \n"); 15 k = atoi(ch); 16 ch = strtok(NULL, " \n"); 17 p = atoi(ch); 18 //printf("%d %d %d\n", n, k, p); 19 fgets(str, sizeof(str), stdin); 20 ch = strtok(str, " \n"); 21 s[0] = ch; 22 for(i=1; i<n; i++){ 23 ch = strtok(NULL, " \n"); 24 s[i] = ch; 25 } 26 //for(i=0; i<n; i++){ 27 //printf("%s\n", s[i]); 28 //} 29 30 //ソート 31 for(i=0; i<n; i++){ 32 for(j=i+1; j<n; j++){ 33 //for(j=0; j<n-1; j++){ 34 if(strcmp(s[i], s[j])>0){ 35 //printf("1"); 36 //strcpy(tmp, "unkooooooo"); 37 //printf("%s\n", tmp); 38 strcpy(tmp, s[i]); 39 strcpy(s[i], s[j]); 40 strcpy(s[j], tmp); 41 } 42 } 43 //for(i=0; i<n; i++){ 44 // printf("%s\n", s[i]); 45 //} 46 } 47 /* 48 i=0; 49 j=1; 50 //for(j=0; j<n-1; j++){ 51 if(strcmp(s[i], s[j])>0){ 52 //printf("1"); 53 //strcpy(tmp, "unkooooooo"); 54 //printf("%s\n", tmp); 55 strcpy(tmp, s[i]); 56 strcpy(s[i], s[j]); 57 strcpy(s[j], tmp); 58 } 59 60 i=0; 61 j=2; 62 //for(j=0; j<n-1; j++){ 63 if(strcmp(s[i], s[j])>0){ 64 //printf("1"); 65 //strcpy(tmp, "unkooooooo"); 66 //printf("%s\n", tmp); 67 strcpy(tmp, s[i]); 68 strcpy(s[i], s[j]); 69 strcpy(s[j], tmp); 70 } 71 */ 72 73 if(k*p > n) 74 min = n; 75 else 76 min = k*p; 77 78 //出力 79 for(i=k*(p-1); i<min; i++){ 80 //for(i=0; i<n; i++){ 81 printf("%s\n", s[i]); 82 } 83 84 return 0; 85}
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。