数组输出中缺少字符

Character is missing from the output of the array

本文关键字:字符 输出 数组      更新时间:2023-10-16

我正在尝试使用指针和字符反转此字符串,但我得到的输出缺少第 2 个字符,找不到原因。 就像下面的情况一样,我缺少 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++无效。

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

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