【问题标题】:Why it gives me an extra words?为什么它给了我一个额外的词?
【发布时间】:2020-03-28 11:53:22
【问题描述】:

编写并测试您自己的函数 char * funct (char * str, int x) 反转(除了位置 n 处的字符)字符串 str 并返回修改后的 str 作为结果。函数func的使用可以是:

这是主要的:

  #include <iostream>
  #include <cstring>
  using namespace std;
  char* funct(char *str, int x);
  int main() {

  char str1 [] = "Hello cpp";

  cout << str1 << endl; // Hello cpp

  cout << funct (str, 1) << endl; // pepC ollH // the character at position 1 ('e') stays in place
  return 0;
  }

这是我的功能:

char* funct(char *str, int x) {

int counter = 0;
do {
    counter++;
    str++;
} while (*str);
str--;
char *wskTmp = str;
for (int i = 0; i < counter ; i++) {

    *wskTmp = *str;
    str--;
    wskTmp++;
}
*wskTmp = '\0';
wskTmp = wskTmp - counter;

for (int i = 0; i < counter - x -1; i++) {
    wskTmp++;
}
char tmp;
for (int i = 0; i < counter-3; i++) {
    tmp = *(wskTmp - 1);
    *(wskTmp - 1) = *wskTmp;
    *wskTmp = tmp;
    wskTmp--;
}

return str;
}

输出:

你好 Cpp

你好 CppepC ollH

应该是:

你好 Cpp

pepC ollH

为什么它在“pepC ollH”之前给我 Hello Cp?

【问题讨论】:

  • 我试图返回 wskTmp,它给了我 epC ollH。 “e”之前的“p”在哪里???????
  • wskTmp 设置为字符串的末尾,然后您进一步增加它,这会导致错误。你想完成什么?

标签: c++ function pointers


【解决方案1】:

您的代码非常混乱,是完成这项任务的一种非常迂回的方式,因此我对其进行了一些重组:

#include <cstring>
#include <iostream>
using namespace std;
char *funct(char *str, int x) {
    // keep track of the original start
    char *origStr = str;
    // iterate through the string to find the end
    do {
        str++;
    } while (*str);
    // decrease the string so it's on the last byte, not the nullbyte
    str--;
    // create a start and end
    char *start = origStr;
    char *end = str;
    if (start - origStr == x) {
        start ++;
    }
    if (end - origStr == x) {
        end--;
    }
    // if start >= end then we've finished
    while (start < end) {
        // swap values at start and end
        char temp = *start;
        *start = *end;
        *end = temp;
        // move the pointers closer to each other
        start++;
        end--;
        // skip the index x
        if (start - origStr == x) {
            start++;
        }
        // skip the index x
        if (end - origStr == x) {
            end--;
        }
    }
    // make sure to return the actual start
    return origStr;
}
int main() {
    char str1[] = "Hello cpp";

    cout << str1 << endl;  // Hello cpp

    cout << funct(str1, 1) << endl;  // pepC ollH // the character at position 1
                                     // ('e') stays in place
    return 0;
}

【讨论】:

  • 您能否将答案标记为已接受,以便人们知道该问题已被回答?
  • 没问题,很高兴能帮到你!
  • 不适用于 x = 0。H 应保持在位置 0。哇。 2 UV 和接受的答案
  • @ArminMontigny 我已经编辑了我的帖子来解决这个问题。不过没必要粗鲁。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多