c++ - 数组的输出中缺少字符
问题描述
我正在尝试使用指针和字符来反转这个字符串,但是我得到的输出缺少第二个字符并且找不到原因。就像在下面的情况下,我错过了 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。
相反,您可以int size
通过 a 获得资格,constexpr
并且没问题。
constexpr int size = 10;
请参阅以下不使用字符指针的示例:https ://rextester.com/AEULY24804
请参阅以下使用 char 指针的示例:https ://rextester.com/FNPW17676
推荐阅读
- c# - 如何在某个日期之后读取日志文件?
- php - Firebase 远程身份验证
- python - Jupyther 中相同值的相同 pandas 哈希,但在导出到 Bigquery 时没有
- multithreading - OTL TOmniBlockingCollection(COM 多线程)中的 CoInitialize/CoUninitialize 错误处理
- flutter - 请求 textDocument/codeAction 失败。消息:无效的文件路径代码:-32003
- google-search-console - 无法在搜索控制台中验证我的 Google 网站页面
- sql - ORA-00907 缺少右括号
- javascript - 在 v-if 语句中使用三元表达式会在 Vue JS 中出错
- java - CachePut如何获取返回值和Id?
- cakephp - 烘烤模型或其他东西时,Twig 崩溃