[英]Strange output from C++ in Linux Terminal
I've recently started learning programming using the C++ language. 我最近开始使用C ++语言学习编程。 I wrote a simple program that is supposed to reverse a string which I compile in the Terminal using gcc/g++. 我编写了一个简单的程序,该程序应该将我在终端中使用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;
}
I've rewritten it multiple times but I always get the same output: 我已经重写了多次,但始终得到相同的输出:
Type something: banana
��
Has anyone had a problem like this or know how to fix it? 有没有人遇到这样的问题或知道如何解决?
Your code initializes index
to -1, and then uses str[index]
but a negative index has no rational meaning in C++. 您的代码将index
初始化为-1,然后使用str[index]
但是负索引在C ++中没有任何合理含义。 Try instead initializing it like so: 尝试像这样初始化它:
index = str.length() - 1;
I can see several issues with your code. 我可以看到您的代码有几个问题。 Firstly, you are initializing index
to -1
, and then decrementing it. 首先,将index
初始化为-1
,然后将其递减。 Maybe you meant auto index = str.length()-1;
也许您的意思是auto index = str.length()-1;
? ?
I recommend you look at std::reverse , which will do the job you're after. 我建议您看一下std :: reverse ,它将做您想要的工作。
Your main function then becomes: 您的主要功能将变为:
#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;
}
If you really want to write your own reverse function, I recommend iterators over array indices. 如果您确实想编写自己的反向函数,则建议对数组索引进行迭代。 See std::reverse_iterator for another approach. 有关另一种方法,请参见std :: reverse_iterator 。
Note , the above will simply reverse the order of bytes within the string. 注意 ,上面的内容将简单地反转字符串中字节的顺序。 Whilst this is fine for ASCII, it will not work for multi-byte encodings, such as UTF-8. 尽管这对于ASCII来说很好,但是不适用于多字节编码,例如UTF-8。
You should use a memory debugger like valgrind. 您应该使用像valgrind这样的内存调试器。 It's a good practice to scan your binary with it, and will make you save so much time. 扫描二进制文件是一个好习惯,这样可以节省很多时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.