2016-07-30 61 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; 
} 
相关问题