简体   繁体   English

字符串反向程序崩溃

[英]String reverse program crashes

I am making a program that is reversing a given string.我正在制作一个反转给定字符串的程序。 but i don't know why my program is crashing.但我不知道为什么我的程序崩溃了。 Help will be highly appreciated instead of criticism.帮助将受到高度赞赏而不是批评。 Thanks!谢谢!

#include <iostream>
#include <string>

using namespace std;

string reverse(string );

int main()
{
    string str;
    cout << "Enter a string"<<endl;
    getline (cin, str);
    reverse(str);
}

string reverse (string str)
{
    string str1;
    for(int i = str.length(); i >= 0; i--)
    {
        str1[i] = str[i];
    } 
    return str1;
}

There are at least three problems in your code:您的代码中至少存在三个问题:

  1. You need to have a string with a length prior to accessing it with [], especially when writing to it.在使用 [] 访问它之前,您需要有一个具有长度的字符串,尤其是在写入它时。
  2. The code is trying to access out of bounds.代码试图越界访问。
  3. The algorithm is just copying the string in reverse order, not reversing the string itself.该算法只是以相反的顺序复制字符串,而不是反转字符串本身。

Implementation left as an excercise to the reader.实现留给读者作为练习。

You do not need to reinvent the wheel, use an algorithm!你不需要重新发明轮子,使用算法!

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    string str;
    cout << "Enter a string"<<endl;
    getline (cin, str);
    std::reverse(str.begin(), str.end());
}

You can read more about std::reverse on cppreference.com .您可以在cppreference.com上阅读有关std::reverse更多信息。

str.length()为您提供字符串的长度,但是当您将其用作数组的索引时,您最终会遇到数组越界错误

#include <algorithm>
#include <string>

void reverse_in_place(std::string &str) {
  std::reverse(str.begin(), str.end());
}
std::string copy_and_reverse(std::string str) {
  std::reverse(str.begin(), str.end());
  return str;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM