fork download
  1. 問題文:文字列を保存する構造体word_pairを下記の様に定義する。
  2. typedef struct word_pair{
  3. char longer_word[10];
  4. char shorter_word[10];
  5. char combined_word[20];
  6. int longer_word_length;
  7. int shorter_word_length;
  8. }word_pair_t;
  9. この構造体を新たに作成し、データをセットして返す関数
  10. word_pair_t create_word_pair(char *a, char *b);
  11. を作成せよ。create_word_pairは以下の仕様を満たす。
  12. create_word_pairは2つの文字列a,bを比較し、長い文字列をlonger_wordに、短い文字列をshorter_wordに代入する。また、これらの長さが同じ場合には辞書的に後ろのものをlonger_wordに、前のものをshorter_wordに代入する。もし、a,bがまったく同じ文字列であれば、エラーメッセージを出力した上で、longer_wordに入力された文字列をshorter_wordに空の文字列を代入する。またcombined_wordにはlonger_word とshorter_wordをスペース区切りで結合したものを代入する。
  13. 標準入力から文字列を2つ読み取り、create_word_pairを用いて、新たにそれらのデータが代入された構造体を作成した後に、これらのメンバ変数を全て、標準出力に表示するプログラムを作成せよ。
  14.  
  15. という問題で、とりあえず自分で細かい条件は無視して文字列を標準入力してから構造体のメンバに文字を格納するところまでやろうとしたのですが、strcpyするのに型が違うとコンパイルエラーが出たのですが、型は一緒だと私は思っているため、なぜ違うのかわかりません。
  16. また辞書的に後ろ前をif文でどのように表現すればいいのかと、文字列結合にstrcatを使うと思うのですが、結合の合間にスペースをいれる方法が分かりません。以下自分のコード。
  17. #include<stdio.h>
  18. #include<string.h>
  19.  
  20. #define max 50
  21.  
  22.  
  23. typedef struct word_pair{
  24. char longer_word[10];
  25. char shorter_word[10];
  26. char combined_word[20];
  27. int longer_word_length;
  28. int shorter_word_length;
  29. }word_pair_t;
  30.  
  31. word_pair_t create_word_pair(char *a, char *b);
  32.  
  33.  
  34. int main()
  35. {
  36.  
  37. char a[max],b[max];
  38. word_pair_t *str;
  39.  
  40.  
  41.  
  42. printf("文字列を2つ入力してください。\n");
  43. printf("1つ目:");
  44. scanf("%s\n",a);
  45. printf("2つ目:");
  46. scanf("%s\n",b);
  47. create_word_pair(a,b);
  48.  
  49. printf("長い方の文字列%s\n",str->longer_word);
  50. printf("短い方の文字列%s\n",str->shorter_word);
  51. printf("連結した文字列%s\n",str->combined_word);
  52. printf("長い方の文字列の長さ%d\n",str->longer_word_length);
  53. printf("短い方の文字列の長さ%d\n",str->shorter_word_length);
  54.  
  55. return 0;
  56.  
  57. }
  58.  
  59.  
  60. word_pair_t create_word_pair(char *a, char *b)
  61. {
  62.  
  63.  
  64.  
  65.  
  66.  
  67. int d, e;
  68. char c[max];
  69. word_pair_t *str;
  70. d = strlen(a);
  71. e = strlen(b);
  72. if(d > e){
  73.  
  74. strcpy(str->longer_word, a);
  75. strcpy(str->shorter_word, b);
  76. c = strcat(a,b);
  77. strcpy(str->combine_word, c);
  78. strcpy(str->longer_word_length, d);
  79. strcpy(str->shorter_word_length, e);
  80.  
  81.  
  82. }
  83. if(d < e)
  84. {
  85.  
  86. strcpy(str.longer_word, b);
  87. strcpy(str.shorter_word, a);
  88. c = strcat(a,b);
  89. strcpy(str.combine_word, c);
  90.  
  91. strcpy(str.longer_word_length, e);
  92. strcpy(str.shorter_word_length, d);
  93.  
  94.  
  95.  
  96.  
  97. }
  98.  
  99.  
  100. }
  101.  
Compilation error #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty