2012-03-20 9 views
1

文字列に文字列のメッセージを格納するプログラムを作成しようとしていましたが、実行するたびに正常に後ろに書きますが、他のときはランダムな文字を最後に追加しますこれ:ランダムなアスキー文字が表示されます

入力:この後方

を書き込むsdrawkcab siht etirw

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
string message; 
getline(cin, message); 
int howLong = message.length() - 1; 
char reverse[howLong]; 
for(int spot = 0; howLong >= 0; howLong--) 
{ 
    reverse[spot] = message.at(howLong); 
    spot++; 
} 
cout << reverse; 
return 0; 
} 
+6

C++はVLAをサポートしていません – ipc

答えて

4

それがnull終止バイトを格納することができるように、長さがmessage.length() + 1する必要があるreverseバッファ。 (ヌル終了バイトは、そのバッファの最後の位置に配置する必要があります)。

+0

'char reverse [howLong];'は何をしますか?コンパイラはどのように動的長さの 'char []'にスペースを割り当てますか?私は何かが欠けているに違いない:\ [またはそれはUBですか?] – amit

+0

@amit、それはC99と互換性があるGCCの拡張だと思います。 –

2

実行時にのみ既知の長さの配列を宣言することはできないため、代わりにコンテナを使用する必要があります。

std::vector<char> reverse(message.length()); 

また、std::stringを使用してください。

std::string reverse(message.rbegin(), message.rend(); 
1

代わりに文字バッファに反転する、新しい文字列を構築する必要があります:STLはまた、例えば、コンストラクタ呼び出しで逆転した文字列を構築し、あなたにいくつかの素晴らしい機能を提供しています。バグが発生しにくく、簡単です。

string reverse; 
for(howlong; howLong >= 0; howLong--) 
{ 
    reverse.push_back(message.at(howLong)); 
} 
1

適切なC++ソリューションを使用してください。あなたが本当にC文字列を逆に文字列を保存する必要がある場合は、あなたを

#include <iostream> 
#include <string> 
#include <algorithm> 

using namespace std; 

int main() { 
    string message, reversed_message; 
    getline(cin, message); 

    //reverse message 
    reversed_message = message; 
    reverse(reversed_message.begin(), reversed_message.end()); 

    //print the reversed message: 
    cout << reversed_message << endl; 
    return 0; 
} 

#include <iostream> 
#include <string> 
#include <algorithm> 

using namespace std; 

int main() { 
    string message; 
    getline(cin, message); 

    //inline reverse the message 
    reverse(message.begin(),message.end()); 

    //print the reversed message: 
    cout << message << endl; 
    return 0; 
} 

は、メッセージ文字列のコピーをリバース:

インラインメッセージを逆転しますできます:

char *msg = (char *)message.c_str(); 

しかし、経験則として、可能であればC++ STL文字列を使用してください。

関連する問題