我最近开始使用C ++语言学习编程。我写了一个简单的程序,它应该反转一个字符串,我使用gcc / g ++在终端中编译。
#include <iostream>
using namespace std;
string reverse_string(string str)
{
string newstring = "";
int index = -1;
while (str.length() != newstring.length())
{
newstring.append(1, str[index]);
index -= 1;
}
return newstring;
}
int main()
{
string x;
cout << "Type something: "; cin >> x;
string s = reverse_string(x);
cout << s << endl;
return 0;
}
我已多次重写它,但我总是得到相同的输出:
Type something: banana
��
有没有人有这样的问题或者知道如何修复它?
答案 0 :(得分:2)
您的代码将index
初始化为-1,然后使用str[index]
,但负索引在C ++中没有合理含义。尝试初始化它,如下所示:
index = str.length() - 1;
答案 1 :(得分:2)
我可以看到您的代码有几个问题。首先,您要将index
初始化为-1
,然后再将其递减。也许你的意思是auto index = str.length()-1;
?
我建议您查看std::reverse,这将完成您之后的工作。
您的主要功能将变为:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x;
cout << "Type something: ";
cin >> x;
reverse(x.begin(), x.end());
cout << x << endl;
return 0;
}
如果你真的想编写自己的反向函数,我建议使用迭代器而不是数组索引。有关其他方法,请参阅std::reverse_iterator。
注意,上面只会反转字符串中的字节顺序。虽然这适用于ASCII,但它不适用于多字节编码,例如UTF-8。
答案 2 :(得分:0)
你应该使用像valgrind这样的内存调试器。 用它扫描你的二进制文件是一个很好的做法,它会让你节省很多时间。