首页 > 解决方案 > 数组的输出中缺少字符

问题描述

我正在尝试使用指针和字符来反转这个字符串,但是我得到的输出缺少第二个字符并且找不到原因。就像在下面的情况下,我错过了 B 这个词。

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


int main()
{

        int size = 100;
        char oldText[size];
        char newText[size];

        char *pntr;
        pntr = oldText;

        cout << "Write the Text: \n";
        for (int i=0; i<size; i++)
        {


            cin.get(pntr,size);
            newText[i]=*pntr;
            cout << *pntr;
            pntr++;
        }

        cout << "The text backwards is: \n";
        for (int i = size; i>=0; i--)
        {
            pntr--;
            cout <<newText[i];


        }
        cout <<endl;


    return 0;
}

结果供您参考

标签: c++pointersc-strings

解决方案


此处的代码不是有效的 C++。

int size = 100;
char oldText[size];
char newText[size];

您使用的 VLA 不是有效的 C++ 代码。阅读此答案以获取更多信息https://stackoverflow.com/a/54674671/7185790

相反,您可以int size通过 a 获得资格,constexpr并且没问题。

constexpr int size = 10;

请参阅以下不使用字符指针的示例:https ://rextester.com/AEULY24804

请参阅以下使用 char 指针的示例:https ://rextester.com/FNPW17676


推荐阅读