教授在C++中“新”的例子在我的机器上不起作用
Professors example of `new` in C++ will not work on my machine
这是教授的代码:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
#include <new>
int main()
{
char *p;
int index = 8;
cout << "Input how many characters:";
cin >> index;
p = new char [index + 1];
cin >> p;
cout << "p is: " << p;
delete [] p;
p = NULL;
return 0;
}
在我用数字回答"多少个字符"语句后,程序停止。
有人知道为什么吗?
首先你有
cin >> index;
您必须在其中输入字符数。
然后你有
cin >> p;
您必须输入一些字符 - 但不超过您之前给出的数字。你在这样做吗?给出另一个提示可能会有所帮助:
cout << "Input up to " << index << " characters:";
cin >> p;
我希望您的教授能够跟进对缓冲区溢出、输入验证、异常安全以及如何使用std::string
来避免手动分配的失误。否则,你就会被教导一些非常坏的习惯。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 编译在我的 Mac 上工作,但在集群 (Linux) 上不起作用
- 为什么我的数组双精度函数不起作用?
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- C++ - 块不移动,我的数组不起作用
- 我不明白为什么我的代码不起作用并且需要更长的时间来运行
- EOF有更安全的替代方案吗?它在我的情况下不起作用
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- binary_search() 函数在我的函数体中不起作用
- 为什么我的打印功能不起作用?链表
- 为什么我的 arduino 按钮在 0 和 1 以外的端口上不起作用?
- 为什么我的数组或函数不起作用?
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- 我有一个应该打印数组的函数,但由于某种原因它不起作用
- 当我的阵列达到一定大小时,Qt 不起作用
- 如果我更改函数输入,我的递归不起作用?
- 断言无符号的 int 确实是积极的不起作用?