2016-07-30 16 views
-2

有人可以告訴我爲什麼這不起作用嗎? 我要檢查,如果一個詞是迴文(不使用reverse()方法)反轉一個沒有reverse()方法的字符串。我在做什麼錯

bool check(const string & s) 
{ 
    string temp; 
    int count = 0; 

    for (long i = s.size() - 1; i >= 0; i--, count++) 
     temp[count] = s[i]; 

    cout << temp; 
    if (temp == s) 
     return true; 
    else 
     return false; 
} 
+0

調整你的字符串'temp'到s'的'大小啓動循環之前。 –

+0

temp被聲明爲字符串,你正在使用它作爲數組? –

+0

「這不起作用」不是一個可接受的問題陳述。 –

回答

3

讓我們看看這兩個具體線路:

string temp; 

    temp[count] = s[i]; 

在第一行聲明一個字符串對象。然後在第二次嘗試寫入空字符串的索引count。由於字符串爲空,索引將超出範圍。索引出界導致未定義的行爲

取而代之的是第二行可以是例如

temp += s[i]; 

這將字符附加到字符串temp,和根據需要延伸的字符串。

或者你可以在臨時字符串的大小設置爲相同大小的輸入字符串:

string temp{s,size(), ' '}; 
+0

非常感謝您的解釋! – mgor3k

1

你有兩個選擇來糾正你的代碼:

  1. 定義臨時字符串的大小。

    char temp[s.size]; //Something similar to this.

  2. string temp;創建一個空字符串,你可以使用附加賦值運算符的反向字符串追加到空字符串。 temp+=s[i];

以下是更正代碼:

bool check(const string & s) 
{ 
    string temp; 
    //int count = 0; 

    for (long i = s.size() - 1; i >= 0; i--) 
     temp += s[i]; 
     //temp[count] = s[i]; 

    cout << temp; 
    if (temp == s) 
     return true; 
    else 
     return false; 
} 
相關問題