-4

基本的に私がしなければならないことは、自分のc-stringを作り直すことです。strlen、strcmp、strcpy、および strcat。以下のコードは私のヘッダーファイルにあります:

int mystrlen(const char pcString[]) //strlen function
{
   const char *pcStringEnd = pcString;

   while (*pcStringEnd != '\0')
      pcStringEnd++;

   return pcStringEnd - pcString;
}

int mystrcmp(char *s1, char *s2) // strcmp function
{
  while(*s1 == *s2)
  {
    if(*s1 == '\0' || *s2 == '\0')
      break;

    first++;
    second++;
  }

  if(*first == '\0' && *second == '\0')
    return (0);
  else
    return (-1);
}

char mystrcpy(char *s1, const char *s2) // strcpy function
{
  while(*s2)
  {
    *s1 = *s2;
    s2++;
    s1++;
  }

 *s1 = '\0';
}

char mystrcat(char *s1, const char *s2) //strcat function
{
  char *string1 = s1;
  const char *string2 = s2;
  char *catString = string1 + string2;
  return catString;
}

ほとんどのエラーは識別子が定義されていないことですが、問題は main.cpp の内容を変更できないことです。ヘッダー ファイルのみを変更できます。ここに main.cpp を配置しますが、長いコードです。

{
 char *string1 = s1;
 const char *string2 = s2;
 char *catString = string1 + string2; //There is an error here with string 2 and catring.
 return catString;
}
4

2 に答える 2

4

変数 first と second の定義がありません (ここで使用:)

first++;
second++;

char* first = /*Whatever*/, *second = /*Whatever*/関数の先頭に追加する必要がありますmystrcmp

しかし、あなたは本当に間違いを犯し、書きたかったと思います

s1++;
s2++;

上記のスニペットの代わりに (さらに同じ関数内で)

于 2013-07-03T21:28:15.053 に答える
1

このコードにはいくつかの問題があります。

mystrcmp

  1. パラメータはconst、偶発的な変更を防ぎ、文字列リテラルを渡すことができるようにする必要があります。
  2. 変数firstが宣言されていません。
  3. 変数secondが宣言されていません。

mystrcpy

  1. 標準ライブラリの関数と一致させようとしている場合、戻り値の型はポインタでなければなりません。
  2. s1値を返すことができるように、値を保存する必要があります。
  3. returnステートメントがありません。

mystrcat

  1. 標準ライブラリの関数と一致させようとしている場合、戻り値の型はポインタでなければなりません。
  2. 関数の本体は完全に間違っています。2 つのポインター値を加算しても、期待どおりに動作しません。ポインター値にp1 + p2なり、それらが指すデータにアクセスしたり変更したりしません。

以下は、宿題をコンパイルするために必要な変更です。を除いて、私はそれをテストしたり、ロジックの多くを変更したりしていませんmystrcat。上記のメモからのコメントも含めました。

int mystrlen(const char *pcString) //strlen function
{
    const char *pcStringEnd = pcString;

    while (*pcStringEnd != '\0')
        pcStringEnd++;

    return pcStringEnd - pcString;
}

// added const to parameters
// changed first to s1
// changed second to s2
int mystrcmp(const char *s1, const char *s2) // strcmp function
{
    while(*s1 == *s2)
    {
        if(*s1 == '\0' || *s2 == '\0')
            break;

        s1++;
        s2++;
    }

    if(*s1 == '\0' && *s2 == '\0')
        return (0);
    else
        return (-1);
}

// changed return type to a pointer
// added variable to save start of s1
// added return statement
char* mystrcpy(char *s1, const char *s2) // strcpy function
{
    char *start = s1;

    while(*s2)
    {
        *s1 = *s2;
        s2++;
        s1++;
    }

    *s1 = '\0';

    return start;
}

// changed return type
// replaced entire function body
char *mystrcat(char *s1, const char *s2) //strcat function
{
    mystrcpy(s1 + mystrlen(s1), s2);
    return s1;
}
于 2013-07-03T21:52:17.447 に答える