【问题标题】:Reversing a String With Pointers用指针反转字符串
【发布时间】:2015-11-03 13:30:54
【问题描述】:

我正在尝试编写一个简单的程序,该程序将利用指针反转用户输入。这是我第一次使用指针,理论上我的程序似乎可以工作:有一个数组,将用户输入写入数组,将一个指针指向头部,另一个指向结尾,并让 while 循环执行休息。但是,我的程序运行不正常。我的问题是,我到底做错了什么?

这是我的代码:

#include <iostream>
#include <string>
using namespace std;

int main() {

    char user_input[1000] = " ";

    cout << "Enter a word to be reversed: " << endl;
    cin >> user_input;

    int myChar = sizeof(user_input) - 1;

    char *start = user_input;
    char *end = user_input + myChar - 1;

    while (start < end) {
        char save = *start;
        *start = *end;
        *end = save;

        start++;
        end--;
    }

    cout << user_input;

} 

And my output: 

Enter a word to be reversed: 
hello <--- my input
      <--- no output

【问题讨论】:

  • My question is, what exactly am I doing wrong? 你没有使用 STL,std::stringstd::reverse
  • 如果我输入的单词超过 999 个字符会怎样?
  • @ChristianHackl - 你会在哪里找到一个? ;)
  • @owacoder:德语语法允许无限长的复合词。让我们看看……“Computerproblemlösungskompetenzseminarlehrergehaltsverhandlungspausengrund。” - 暂停讨论研讨会教师工资以解决计算机问题的原因。您可以随意扩展它,甚至使其递归。 (但在你继续这样做之前,请注意,即使语法允许,好的风格是另一回事:))

标签: c++ pointers


【解决方案1】:

线

int myChar = sizeof(user_input) - 1;

应该是

#include <string.h>

int myChar = strlen(user_input);

目前,您正在反转数组中的所有 1000 个字符。超出输入字符串末尾的字符未初始化,因此您应该只反转用户输入的字符数。 strlen() 为您找到长度。

另一种选择:使用标准库。

【讨论】:

  • 谢谢!我在学习中错过了 strlen()。
【解决方案2】:

sizeof(user_input) 始终为 1000,因为 user_input 是一个由 1000 个 1 字节元素组成的数组。

您需要改用strlen。它返回终止空字符的索引。

【讨论】:

    【解决方案3】:

    将 user_input 声明为 char *user_input=new char[1000]


    那么问题出在哪里?


    问题是当您在 user_input 中获取用户的输入时,它会将其作为 user_input[0] 所以要么运行一个从 0 到 n-1 的 for 循环,要么使用我上面给出的方式 而且输出仍然是错误的,我会留给你.....

    【讨论】:

    • 谢谢!我知道更好理解。
    【解决方案4】:

    你也可以自己写一个strlen函数。
    用户输入的结尾将是第一个 0 作为 int 或 '\0' 作为 char 的索引。

    【讨论】:

      猜你喜欢
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-26
      相关资源
      最近更新 更多