我试图在C++中反转char数组.这是我的代码:
void reverse(char s[]);
int main()
{
char s [] = "Harry";
cout << reverse(s) << endl;
system("PAUSE");
return 0;
}
void reverse(char s[])
{
if( strlen( s ) > 0 ) {
char* first = &s[ 0 ];
char* last = &s[ strlen( s ) - 1 ];
while( first < last ) {
char tmp = *first;
*first = *last;
*last = tmp;
++first;
--last;
}
return;
}
Run Code Online (Sandbox Code Playgroud)
但是,我在cout << reverse(s)<< endl; 位于main方法中的那行,我不知道为什么.错误消息是没有操作符匹配这些操作数.有人可以帮我解决这个问题吗?
提前致谢.
Jos*_*eld 11
您的reverse
函数的返回类型为void
.这意味着它不会返回任何内容,因此您cout << reverse()
无需输出任何内容.
相反,你打算这样做:
char s [] = "Harry";
reverse(s);
cout << s << endl;
Run Code Online (Sandbox Code Playgroud)
或者,您可以reverse
返回char*
并放在return s;
其身体的末尾.但是,这有点奇怪,因为您同时使用参数和返回值作为相同的函数输出.只需按上述方法使用即可.
当然,如果你使用标准库,你可以更容易地做到这一点; 使用std::string
和std::reverse
:
std::string s = "Test";
std::reverse(s.begin(), s.end());
std::cout << s << std::endl;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
144 次 |
最近记录: |