用指针反转字符串

mur*_*7ay 0 c++ pointers

我正在尝试编写一个简单的程序,它将使用指针反转用户输入.这是我第一次使用指针,理论上我的程序似乎可以工作:有一个数组,将用户输入写入数组,指向头部的一个指针,另一个指向结尾,并使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
Run Code Online (Sandbox Code Playgroud)

owa*_*der 5

这条线

int myChar = sizeof(user_input) - 1;
Run Code Online (Sandbox Code Playgroud)

应该

#include <string.h>

int myChar = strlen(user_input);
Run Code Online (Sandbox Code Playgroud)

目前,您正在反转阵列中的所有1000个字符.输入字符串末尾之外的字符未初始化,因此您只应反转用户输入的字符数.strlen()找到你的长度.

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