未初始化的对象?这段代码有什么问题。
Uninitialized object? What's wrong with this code.
由于某种原因,代码崩溃并给我一个访问违规错误。它一直说对象用户没有初始化
随机编码中0x0F45E89A (msvcr110 .dll)的第一次机会异常在c++ .exe: 0xC0000005:访问冲突写入位置0 xabababab。未处理的异常0x0F45E89A (msvcr110 .dll)在随机在c++ .exe中编码:0xC0000005:访问违反写入位置0 xabababab。
谢谢。什么好主意吗?
#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct User {
string name; //Both first and last name go here
int birthYear;
string major;
};
int main()
{
ifstream input("input.txt");
if(!input || !input.is_open())
return -1;
string buffer;
int count = -1;
int index = 0;
int size;
User* users;
while(getline(input, buffer, 'n'))
{
stringstream ss(buffer);
if(count == -1)
{
ss >> size;
users = new User[size];
count = 0;
}
else
{
if(count == 0)
{
users[index].name = buffer;
count++;
}
if(count == 1)
{
ss >> users[index].birthYear;
count++;
}
if(count == 2)
{
users[index].major = buffer;
count = 0;
index++;
}
}
}
for(int i = 0; i < 2; i++)
{
cout<<users[i].name << " " << users[i].birthYear << " " << users[i].major <<endl;
}
system ("PAUSE");
return 0;
}
for(int i = 0; i < 2; i++)
{
cout<<users[i].name << " " << users[i].birthYear << " " << users[i].major <<endl;
}
看起来incoorect。您如何确定用户至少包含两个元素?如果getline
因为坏文件而失败,或者第一行显示只有1条记录,您将得到上述异常。
你应该把循环改成
// Initialize size with 0 before while(getline) loop
for(int i = 0; i < size; i++)
{
cout<<users[i].name << " " << users[i].birthYear << " " << users[i].major <<endl;
}
下面的代码看起来也有问题
if(count == 0)
{
users[index].name = buffer;
count++;
}
if(count == 1)
{
ss >> users[index].birthYear;
count++;
}
if(count == 2)
{
users[index].major = buffer;
count = 0;
index++;
}
当count为0时,它将进入first if条件并被加1。然后条件count == 1
为真,你也会遇到下两个条件。您应该将接下来的2个if
条件替换为else if
,或者将switch
语句替换为break
语句,以查看预期的行为。
另外,在你使用完它之后,让用户免费使用也是一个很好的做法。
我认为第一个getline
失败了(while没有进入,所以没有创建任何东西),您自动到达for循环。检查是否有用户
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 0-1背包代码中的错误.我的代码中有什么错误
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 这行代码在C++类中意味着什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 以下 C++ 代码用于 -> "#define idiv(a, b) (((a) + (b) / 2) / (b))" 是什么?
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 此代码中的操作流程是什么?C/C++.
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 此代码验证公式是什么意思?
- 需要以下代码的帮助,下面的代码有什么问题
- C++标准提案代码:什么是 N 和 P?
- C - 哈希算法代码什么都没有返回
- 将"12345678"转换为"1-234-5678",我的代码什么也没产生
- 在编译过程中,琐碎的(没有效果的)代码什么时候会被删除
- 有人能告诉我为什么这个代码什么都不打印吗