實際上,我工作的一個C++字符串反轉/字符[]的方法C++做它想要的東西|的char [] cout和倒置的char []
#include <iostream>
using namespace std;
void inverse(string input)
{
int length = input.length();
char* output = new char[length];
for(int i = 0; i < length; i++)
{
output[length - (i + 1)] = input[i];
}
cout << output << endl;
delete output;
}
int main(int argc, char *argv[])
{
while(true)
{
string in;
cin >> in;
inverse(in);
}
return 0;
}
的問題是,當我輸入一個字符串3/5/7等如果它是正確的,但是如果我輸入一個字符串長度爲2/4/6等等字符那裏反轉字符串在他和和只有當我輸入這些長度的數字時有隨機字符。
我很困惑,因爲這個錯誤只出現在偶數。
這裏有一個小例子: Here's a little example:
下面是新的代碼(一切正常這裏),我知道它有話對數組的末尾做的/ 0,但爲什麼只有偶數。
#include <iostream>
using namespace std;
void inverse(string input)
{
int length = input.length();
char* output = new char[length + 1];
for(int i = 0; i < length; i++)
{
output[length - (i + 1)] = input[i];
}
output[length] = '\0';
cout << output << endl;
delete output;
}
int main(int argc, char *argv[])
{
while(true)
{
string in;
cin >> in;
inverse(in);
}
return 0;
}
任何人都可以幫我找到解決方案嗎?
對於初學者來說,你錯過的#include''。另外:查找['std :: reverse'](http://en.cppreference.com/w/cpp/algorithm/reverse)。 –
rubenvb
爲什麼'字符*輸出=新的char [長度+ 1];'代替'的std :: string輸出(長度+ 1,0);',你已經採取了'的std :: string'作爲參數。 –
我同意Ralph Tandetzky答案。 我注意到你的應用程序中存在內存泄漏,你需要刪除整個數組。 所以'刪除輸出;'應該'刪除[]輸出' –