这个c ++反向字符串函数有什么问题 [英] Whats wrong with this c++ reverse string function
本文介绍了这个c ++反向字符串函数有什么问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void reverse (char s[]){
int len = strlen(s);
int j = len - 1;
for (int i = 0; i < j; i++,j--){
cout << s[i];
char ch = s[i];
s[i] = s[j]; //error line - giving exception, cannot write to the memory
s[j] = ch;
}
}
我使用Visual Studion 2008,理解什么是这里的问题..:.. ..我从C ++实践:$。
I am using Visual Studion 2008 and i can't understand whats the problem here .. :s .. I am out of C++ practice :$ .
推荐答案
问题是使用C风格字符串而不是C ++风格字符串。特别是,你显然试图写一个常量字符串字面值:
The problem is that it uses C-style strings instead of C++ style strings. In particular, you are apparently trying to write to a constant string literal:
char const* str = "I cannot be written to";
C ++允许忽略 const
最后,C ++已经有一个反向
function:
Finally, C++ already has a reverse
function:
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string str = "Hello world";
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
}
这篇关于这个c ++反向字符串函数有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文