【发布时间】:2013-06-11 05:55:47
【问题描述】:
这是我的代码:
int main ()
{
const int MAX = 10;
char *buffer = nullptr; // used to get input to initialize numEntries
int ARRAY_SIZE = 20; // default is 20 entries
int numEntries;
success = false;
while (!success)
{
delete buffer;
buffer = nullptr;
buffer = new char [MAX];
cout << "How many data entries:\t";
cin.getline(buffer, MAX, '\n');
cout << endl << endl;
while (*buffer)
{
if (isdigit(*buffer++))
success = true;
else
{
success = false;
break;
}
}
}
numEntries = atoi(buffer);
问题是当我输入一个任意数字时,它只显示“numEntries = 0”,如果我输入一个字符串,它就会崩溃。
有人能解释一下到底发生了什么吗?
【问题讨论】:
-
用
delete []删除数组 -
使用
std::string而不是char*的麻烦会更少:cplusplus.com/reference/string/string/getline -
您的代码与问题不匹配:您在哪里打印“numEntries = ??” ?此外,您的 while 循环有问题
success将根据数组中的最后一个字符设置,而不是整个设置。 -
这段代码简直坏了。您分配了一个
char数组并将其存储在buffer中,但随后您将buffer移动到其他位置。稍后对其调用delete只是未定义的行为(它应该是delete[],因为您分配了一个数组)。 -
@rajraj 在空指针上调用
delete(或delete[])保证无操作,无需事先检查。