c++ - 数组未正确分配

标签 c++ visual-studio-2008

我正在尝试编写一个接受用户输入文件名的程序。从那里它将文件中的数字存储到一个数组中,对它们进行排序,然后显示它们。但是,我得到了类似于访问越界数组的大量数字,但我可以从调试器中看出我不是。

  #include <iostream>
using namespace std; 

class TestScores
{ 
public:
    TestScores();

    TestScores(int scores);

    ~TestScores();

    void AddScore(int newScore);

    void DisplayArray();

    void SortScores();

    bool ArraySorted();

    int AvgScore();

private:
    int *scoresArray;  //Dynamically allocated array 
    int numScores;  //number of scores input by user
    int scoreCounter;
    const static int default_NumArrays=10; //Default number of arrays
};

#include <iostream>
#include "TestScores.h"

TestScores::TestScores()
{
    scoresArray=new int[default_NumArrays];
    scoreCounter=0;
    numScores=default_NumArrays;
}

TestScores::TestScores(int scores)
{
    scoresArray=new int[scores];
    numScores=scores;
    scoreCounter=0;
    for(int i=0; i<scores;i++)
        scoresArray[i]=0;
}

TestScores::~TestScores()
{
    delete[] scoresArray;
}

void TestScores::AddScore(int newScore)
{
    if(scoreCounter<numScores){
        scoresArray[scoreCounter]=newScore;
        scoreCounter++;
    }
    else
        cout<<"More scores input than number of scores designated"<<endl;
}

void TestScores::DisplayArray()
{
    for(int i=0; i<numScores; i++)
        cout<<scoresArray[i]<<endl;
    cout<<endl<<"This is scoresArray"<<endl;
}

bool TestScores::ArraySorted()
{
    for(int i=0; i<(scoreCounter-1);i++){
        if(scoresArray[i]<=scoresArray[i+1])
            continue;
        else
            return false;
    }
    return true;
}

void TestScores::SortScores()
{
    int tempValue;

    while(ArraySorted()!=true){
        for(int i=0; i<(scoreCounter-1); i++){
            if(scoresArray[i]<=scoresArray[i+1])
                continue;
            else{
                tempValue=scoresArray[i+1];
                scoresArray[i+1]=scoresArray[i];
                scoresArray[i]=tempValue;
            }
        }
    }
}


int TestScores::AvgScore()
{
    int sumScores=0;

    if(scoreCounter>0){
        for(int i=0; i<scoreCounter; i++)
            sumScores+=scoresArray[i];
        return (sumScores/scoreCounter);
    }
    else{
        cout<<"There are no scores stored."<<endl;
        return 0;
    }
}

#include "TestScores.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std; 
//Function prototypes
bool FileTest(ifstream& inData);
void StoreScores(ifstream& inData, int& newNumScores, TestScores satScores);

int main()
{   
    int newNumScores=0;
    string inputFile;   //Contains name of the user file being used

    //Opening file stream
    ifstream inData;

    //User prompt for input file
    cout<<"Please enter the file name containing the student scores you wish to "
        <<"have stored, sorted, and displayed."<<endl;

    cin>>inputFile;

    //Opening file streams
    inData.open(inputFile.c_str());

    while(FileTest(inData)==false){
        cout<<"I'm sorry, the file you entered was not a valid file.  "
            <<"Please enter another file name, or enter q to exit"<<endl;
        cin>>inputFile;
        if(inputFile=="q")
            return 0;

        //Opening file streams
        inData.open(inputFile.c_str());
    }

    inData>>newNumScores;  
    TestScores satScores(newNumScores);   //Instantiating TestScores variable
    StoreScores(inData, newNumScores, satScores);  //Storing scores into array

    satScores.DisplayArray();
    satScores.SortScores();
    satScores.DisplayArray();
    cout<<endl<<"This is the array after sorting"<<endl<<endl;

    cout<<"This is the average score "<<satScores.AvgScore()<<endl;

    //Program pauses for user input to continue
    char exit_char; 
    cout<<"\nPress any key and <enter> to exit\n";
    cin>>exit_char;

    inData.close();

    return 0;   
}


bool FileTest(ifstream& inData)
{
    if(!inData)
    {
        cout<<"Your file did not open.\n";
        return false;
    }
    return true;
}


void StoreScores(ifstream& inData, int& newNumScores, TestScores satScores)
{   
    int userScore;
    while(inData>>userScore){
        satScores.AddScore(userScore);
    }
}

我的测试文件是 random.dat,包含以下内容:

15
67
76
78
56
45
234

通过查看调试器,我可以看出 scoreCounter 正在正确递增并且 newScore 包含下一个值,那么为什么它不存储在数组中呢?感谢您的帮助

最佳答案

好的,问题很简单:您将 satScores 按值传递给 StoreScores。这只会填充本地拷贝,将 StoreScores 的签名更改为以下内容以修复:

void StoreScores(ifstream& inData, int& newNumScores, TestScores& satScores)

(顺便说一句,您实际上并没有使用 newNumScores 变量。) 然后输出符合预期:

15
67
76
78
56
45
234
0
0
0
0
0
0
0
0
0
0

要进一步改进您的代码,请参阅 GMan 的评论和 Ben 的回答。

关于c++ - 数组未正确分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5466896/

相关文章:

c++ - 什么场景可能需要使用\需要指向(非常量\常量)数据的常量指针

c++ - 类的堆分配对象是否在其范围之后但在 C++ 中调用其析构函数之前仍然存在

c++ - 类声明后的初始化 C++

c++ - 隔离字符中的 1 字符串

c# - 如何强制 MSTEST TestMethod 在运行前重置所有单例/静态?

c - 在 Visual Studio 2008 或 2010 中将 Lua 嵌入到 C 应用程序中

c# - 如何通过 C# 使用 Java Applet?

java - 套接字通信协议(protocol)/标准

c++ - Visual Studio 2008 中的内存和寄存器面板丢失

c# - WCF 服务默认值