【问题标题】:Trying to reverse a C string试图反转 C 字符串
【发布时间】:2020-06-28 00:46:56
【问题描述】:

我不能使用除strlen() 之外的任何c 函数,我也不能使用字符串。不幸的是,我在这方面已经有一段时间了。作为输出的一部分,我不断收到奇怪的字符。即问号和本质上奇怪的替代代码就是它的样子。

#include <iostream>
#include <cstring>

using namespace std;

int lastIndexOf(const char*, char[]);
void reverse(char*);
int replace(char*, char, char);

int main() {
  int i = 0, count = 0, counter = 0, SIZE = 100;
  char charArray[SIZE];
  cout << "Enter a string of no more than 50 characters: ";
  cin.getline(charArray, SIZE);
  reverse(charArray);
}

void reverse(char s[])
{
  int n = 100;

  for (int i = 0; i < n / 2; i++) {
    swap(s[i], s[n - i - 1]);
    cout << (s[i]);
  }
}

我尝试了几种不同的方法,swap 函数,使用指针手动将它们与临时变量交换。所以我去网上看看其他人做了什么,但无济于事。我相信有一个简单的解决方案。

【问题讨论】:

  • 你为什么认为用户输入了正好 100 个字符?
  • int n = 100; 是你的错误,
  • 提示:你告诉我们你可以使用strlen,但你永远不会在你的代码中使用它!为什么你认为你需要被允许使用那个功能?知道字符串的长度在哪里很重要? (另见上述评论)。
  • fwiw,这不是最简单的事情。不要害怕,因为你期望事情很简单,但你却在挣扎。东西不简单。只有当你设法让它工作时,任何事情都是“简单的”
  • @God_Zilla121 为什么你可以使用std::swap() 而不是std::reverse()?在任何情况下,int n = 100; 都应该是 int n = strlen(s);。或者更好的是,在您的reverse() 函数中添加一个size 参数,然后您可以使用cin.gcount() 作为大小,根本不需要strlen()

标签: c++ algorithm reverse c-strings function-definition


【解决方案1】:

函数使用幻数 100

int n = 100;

虽然在 main 中提示输入不超过 50 个字符。

cout << "Enter a string of no more than 50 characters: ";

您需要使用标准C函数strlen来计算传递字符串的长度。

函数可以如下所示

char * reverse( char s[] )
{
    for ( size_t i = 0, n = std::strlen( s ); i < n / 2; i++ )
    {
        std::swap( s[i], s[n-i-1] );
    }

    return s;
}

请注意,可变长度数组不是标准 C++ 功能。

你应该写

const size_t SIZE = 100;
char charArray[SIZE];

【讨论】:

    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多