1

文字列を逆にするコードを書きました

#include < iostream >
#include < cstring >

using namespace std;

string Reversal(char * s);

int main()
{
    char str[25];

    cout << "Enter a Name :";

    cin.get(str, 25);
    cout << "You have entered: " << str;

    cout << "\nReversed : " << Reversal(str);
    return 0;
}

string Reversal(char * s)
{
    int count = strlen(s);
    char temp[count];
    for (int i = 0; i < count; i++)
    {
        temp[i] = * (s + (count - 1) - i);
    }
    return temp;
}

以下のリンクを参照して、cin が空白を入力として受け取るようにします。

c ++でスペースをcinする方法は?

しかし、出力にはいくつかのジャンク文字が表示されていますか? なぜそうなのでしょうか? ここに画像の説明を入力

4

2 に答える 2

4

std::stringfromを暗黙的に構築する場合temp、後者は NUL で終了することが期待されますが、そうではありません。

変化する

return temp;

return std::string(temp, count);

tempこれは、明示的な文字数を取り、 NUL で終了することを想定していない別のコンストラクターを使用します。

于 2013-04-01T08:29:55.483 に答える
2

temp 配列の最後の文字は null で終了する必要があります。入力文字列のサイズより 1 長くします。最後の文字をヌル文字 ( '\0') にします。

string Reversal(char *s)
{
 int count=strlen(s);
 char temp[count+1]; //make your array 1 more than the length of the input string
 for (int i=0;i<count;i++)
 {
   temp[i]= *(s+(count-1)-i);
 }

 temp[count] = '\0'; //null-terminate your array so that the program knows when your string ends
 return temp;
}

ヌル文字は文字列の終わりを指定します。通常、すべてのビットが 0 のバイトです。これを一時配列の最後の文字として指定しないと、プログラムは文字配列の終わりがいつなのかわかりません。が見つかるまで、すべての文字を含め続け'\0'ます。

于 2013-04-01T08:31:56.747 に答える