在candidateVotes.exe中以0x50E6F1C0(UCRTBASED.DLL)抛出异常.Exe:0xc00
Exception thrown at 0x50E6F1C0 (ucrtbased.dll) in CandidateVotes.exe: 0xC0000005: Access violation reading location 0x00000000
当我尝试运行程序时,我会收到此通知。
在cantidateVotes.exe中以0x50e6f1c0(ucrtbased.dll)抛出的例外
这是我的代码:
编写一个程序,允许用户输入五个候选人的姓氏在地方选举和每个候选人获得的选票数量中。然后,该计划应输出每个候选人的姓名,收到的票数,以及候选人获得的总票数的百分比。您的计划还应输出选举的获胜者。
void main()
{
string name[5] = { 0 };
int votes[5] = { 0 };
int total = 0;
for (int i = 0; i < 5; i++)
{
cout << "What is the name of Candidate number " << i + 1 << "?" << endl;
cin >> name[i];
cout << "How many votes did " << name[i] << " receive?" << endl;
cin >> votes[i];
total += votes[i];
cout << total << endl;
}
system("pause");
}
问题出现在这里:
string name[5] = { 0 };
这试图构造5个std::string
对象的数组,第一个字符串用0
初始化。
发生时,这调用以下构造函数:
basic_string(const char * const _Ptr)
,然后,一旦删除了无效指针,就会报告访问违规错误。
将null char*
指针传递给std::string
构造函数是未定义的行为。
无需为数组提供初始化器,因为std::string
默认构造函数将正确初始化每个元素:
string name[5];
如果要指示考虑初始化,则以下语法是可以的:
string name[5] = {};
或
string name[5]{};
最后,启用尽可能多的合理警告始终是一个好主意。在带有Level4 (/W4)
的MSVC上,我会收到以下警告:
警告C6387:' param (1)'可以是'0':这不符合函数'std :: basic_string&lt&char,std :: char_traits&char> char>,std ::分配器&lt; char>> :: {ctor}'。
注意这可能避免以后避免一些混乱。
您正在尝试用null构建std::string
。从name
的初始化列表中删除0或完全删除初始化列表。
string name[5];
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- 函数如何通知用户它基于函数原型抛出异常?
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- VisualStudios 会抛出异常,而代码块不会 [C++]
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- ZMQ::send() 抛出异常并终止 QNX 进程.为什么以及如何从中恢复?
- new(std::nothrow) int[n] 抛出异常
- 为什么g_object_set抛出异常(vcruntime140.dll)?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- C++子线程抛出异常
- 我们应该在抛出异常之前取消分配内存吗
- 有没有一种方法可以让OpenCLC++绑定为所有错误抛出异常
- 为什么访问模板化变体作为返回值抛出异常
- 如何实现,错误分配中止而不是抛出异常
- std::p riority_queue::p op什么时候会抛出异常
- 在0x5914F3BE抛出异常(基于.dll)
- std::vector 默认构造函数可以抛出异常吗?
- 挂钩创建文件抛出异常:读取访问冲突
- getaddrinfo 抛出异常
- 在candidateVotes.exe中以0x50E6F1C0(UCRTBASED.DLL)抛出异常.Exe:0xc00