未初始化的对象?这段代码有什么问题。

Uninitialized object? What's wrong with this code.

本文关键字:代码 什么 问题 初始化 对象 段代码      更新时间:2023-10-16

由于某种原因,代码崩溃并给我一个访问违规错误。它一直说对象用户没有初始化

随机编码中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循环。检查是否有用户