我最近开始使用 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
��
有没有人遇到过这样的问题或知道如何解决?
最佳答案
您的代码将 index
初始化为 -1,然后使用 str[index]
但负数索引在 C++ 中没有合理的意义。尝试像这样初始化它:
index = str.length() - 1;
关于c++ - Linux 终端中 C++ 的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481976/