【问题标题】:Character is missing from the output of the array数组的输出中缺少字符
【发布时间】:2019-02-14 12:02:33
【问题描述】:

我正在尝试使用指针和字符来反转此字符串,但我得到的输出缺少第二个字符并且找不到原因。就像在下面的情况下,我错过了 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;
}

Result for your reference

【问题讨论】:

  • 请不要在提问中使用图片。他们没用。而是尝试将图像的上下文粘贴到文本中。
  • istream::get (char* s, streamsize n)n 字符提取到s 中,或者直到遇到分隔符。所以它会在一次调用中提取多达 100 个字符,你为什么要循环调用它?

标签: c++ pointers c-strings


【解决方案1】:

这里的代码不是有效的 C++。

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

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

相反,您可以使用constexpr 来限定int size,这样就可以了。

constexpr int size = 10;

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2013-01-24
    • 2014-09-08
    相关资源
    最近更新 更多