反转字符串的序列

时间:2014-10-26 19:18:59

标签: c++

一个相当简单的程序,尝试在C ++中反转空终止字符串中的字符,但似乎出现了问题。

#include <iostream>

using namespace std;

void reverse(char*);

int main(){

    char *str;
    cout<< "Please enter a string, no spaces please..";
    cin >> str;


    //reverse(str);

}

void reverse(char *str){

    char temp;
    size_t len = strlen(str); 

    for (size_t i = 0; i < len/2; i--)
    {
        temp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = temp;

    }

}

获得以下错误

Bus error: 10

任何帮助表示感谢。

4 个答案:

答案 0 :(得分:2)

  • 使用前为str分配内存char *str = new char[25];

  • reverse循环增量的for函数i for (size_t i = 0; i < len/2; i++ )

  • 使用delete [] str ;

  • 后释放内存

答案 1 :(得分:0)

尝试修改后的代码版本:

#include <iostream>
#include <cstring>

using namespace std;

void reverse(char*);

int main(){

    char str[1024]; // buffer of 1024 chars
    cout<< "Please enter a string, no spaces please..";
    cin >> str;


    reverse(str);
    cout << "\nReversed: " << str;

}

void reverse(char *str){

    char temp;
    size_t len = strlen(str); 

    for (size_t i = 0; i < len/2; i++) // loop until half of the user input
    {
        temp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = temp;

    }
}

我只是添加了char char str[1024];数组来存储用户输入..并将循环更改为:for (size_t i = 0; i < len/2; i++)

但是,你必须对上面的代码非常小心..如果输入的大小小于数组的固定大小,它可以正常工作。

答案 2 :(得分:0)

您正在递减迭代器i而不是递增它。你的一点点紧凑版本:

#include <algorithm>
#include <cstring>

void reverse(char* const str)
{
    unsigned long const len = strlen(str);
    for(unsigned long i = 0; i < len >> 1; i++)
        std::swap(str[len - i - 1], str[i]);
}

答案 3 :(得分:0)

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

int main() {

  // You can't read something to nowhere.
  // String will be holded in static array.
  char str[1024];

  // To keep it as null terminated string after
  // writing of inputed string: `std::cin` don't
  // write null character after writing of data.
  memset(str, 0, 1024);

  std::cin >> str;

  // If you do reversing of strings in C++,
  // you shouldn't use hand written loops: 
  std::reverse(str, str + strlen(str));

  std::cout << str << std::endl;

}