2011-09-17 46 views
1

我得到以下输出:olleh hello但无法弄清楚我要出错的地方!关于反转字符串的问题

int main() 
    { 

     char hello[6] = "hello"; 
     char temp[6]; 
     unsigned int t = 0; 
     for(int i=strlen(hello)-1;i>=0;i--) 
     { 
     if(t<strlen(hello)) 
     { 
      temp[t] = hello[i]; 
      t++; 
     } 
     } 
     cout << temp; 
     return 0; 
    } 
+2

需要你做出临时阵列6元长。但是你从不写第六个元素。零。 –

+0

顺便说一下,你并不需要检查'如果(t RocketR

回答

7

您在字符串的结尾需要一个空终止:

int main() 
{ 

    char hello[6] = "hello"; 
    char temp[6]; 
    unsigned int t = 0; 
    for(int i=strlen(hello)-1;i>=0;i--) 
    { 
    if(t<strlen(hello)) 
    { 
     temp[t] = hello[i]; 
     t++; 
    } 
    } 
    temp[t] = '\0'; 
    cout << temp; 
    return 0; 
} 
3

你是不是有一个空(\0)终止temp,所以temp不是一个有效的字符串,并没有按cout我不知道该怎么处理它。如果添加:

temp[5] = 0; 

for后循环。

+1

“'temp'是一个无效的字符串文字” - 'temp'是一个变量,它不能是一个文字。 –

+1

当然。感谢您的支持。 – adpalumbo

+0

好吧,现在你有我的+1了:) –

7

您标记了一个问题,[C++],所以这里的C++办法扭转字符串:

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

int main() 
{ 
    std::string hello = "hello"; 
    std::reverse(hello.begin(), hello.end()); 
    std::cout << hello << std::endl; 
} 

很难在这里做任何错误