2012-03-20 27 views
1

我試圖編寫一個程序,它將字符串中的消息存儲回字符數組中,並且每當我運行它時,它有時會成功向後寫入,但有時會將隨機字符添加到末尾此:Random ascii char的出現

輸入:寫這個向後

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 2012-03-20 16:11:58

回答

4

緩衝reverse需要是message.length() + 1在長度,使得它能夠存儲一個空終止字節。 (並且空終止字節需要放在該緩衝區的最後一個位置。)

+0

'char reverse [howLong]'會做什麼?編譯器如何爲動態長度的char []分配空間?它編譯沒有ideone問題 - 我必須缺少一些東西:\ [或者它是UB嗎?] – amit 2012-03-20 16:12:31

+0

@amit,我認爲這是一個GCC擴展與C99兼容。 – 2012-03-20 16:14:01

2

由於您無法聲明僅在運行時已知的長度的數組,因此必須使用容器。

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

或更好,請使用std::string。該STL還提供了一些不錯的功能給你,例如建立反向字符串中的構造函數調用:

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

倒車入字符緩衝區相反的,你應該建立一個新的字符串。它更容易,更不易發生錯誤。

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

使用適當的C++解決方案。

內嵌扭轉消息:

#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; 
} 

反向消息字符串的副本:

#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; 
} 

如果你真的需要反向字符串保存在C字符串,你可以這樣做:

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

但是,根據經驗,如果可以,請使用C++ STL字符串。