c++ - Linux 终端中 C++ 的奇怪输出

标签 c++ linux

我最近开始使用 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/

相关文章:

c++ - 我是否正确实现了时钟漂移?

C++内存地址和偏移写/读

c++ - 使用快速排序在 C++ 中排序可视化工具错误

linux - 编译时出现 undefined reference 错误

ruby - 通过 xvfb-run 运行 selenium ruby​​ 脚本时出错

linux - linux中eth1上的静态IP地址

c++ - 如何在 mpi 中发送字符串 vector ?

c++ - C++ 中的运算符 [&]

c# - .NET Core SQLite 'database is locked' 仅在 Linux 上

linux - 什么时候调用setsockopt?在 bind() 和 connect() 之前?