简体   繁体   中英

Reading array from file not giving correct values?

Currently working on a project that must be completed by this Thursday night PST. For a quick summary, the program must be menu based and allow the user to create an array of long doubles (user set number of rows/columns and all array values) and have it save to a file (user set name). It must also allow the user to read a file into an array of long doubles and print it to the program, then allow the user to select a column to sort and save the sorted array into another file, then finally allow the user to search for a value in a file (where the program must know if the columns are sorted or unsorted and use the appropriate search algorithm).

I have not completed CHOICE_4 in the menu because of the issues with CHOICE_2 and CHOICE_3 functions. Here is my source code for the entire project:

#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <fstream>
#include <vector>

using namespace std;

//Function prototypes required for project
void displayMenu(int &);                //Menu function
int unsortedFile(string, int, int);     //Function for menu choice 1
int printFile(string, int, int);        //Function for menu choice 2
int sortFile(string, int, int);     //Function for menu choice 3

int main()
{
    int choice;             //Menu choice

    do
    {
        displayMenu(choice);
    } 
    while (choice > 0 && choice <= 4);

    return 0;
}

void displayMenu(int &c)
{
    //Constants for menu choices
    const int   CHOICE_1 = 1,
                CHOICE_2 = 2,
                CHOICE_3 = 3,
                CHOICE_4 = 4,
                QUIT_CHOICE = 0;

    string  filenameU,      //unsorted
            filenameP,      //printed
            filenameS,      //to be sorted
            filenameSOut;   //sorted data

    int         SIZE1,      //Array dimensions
                SIZE2;      //Array dimensions

    cout << "-------------------------" << endl;
    cout << "\tMENU" << endl;
    cout << "-------------------------" << endl;
    cout << "1. Create a custom array file." << endl;
    cout << "2. Print an array from a file." << endl;
    cout << "3. Sort an array from a file." << endl;
    cout << "4. Search an array from a file." << endl;
    cout << "0. Exit program." << endl;
    cout << "-------------------------" << endl;
    cout << "Enter your choice from above: ";
    cin >> c;
    cout << endl;

    switch(c)
    {
        case CHOICE_1:
            cout << "Enter the name of the file you want to write: ";
            cin.ignore(100, '\n');
            getline(cin, filenameU, '\n');

            do
            {
                cout << endl;
                cout << "Enter the amount of rows you want in your array between 2 and 10: ";
                cin >> SIZE1;
            } while (SIZE1 < 2 || SIZE1 > 10);

            do
            {
                cout << endl;
                cout << "Enter the amount of columns you want in your array between 2 and 10: ";
                cin >> SIZE2;
            } while (SIZE2 < 2 || SIZE2 > 10);

            unsortedFile(filenameU, SIZE1, SIZE2);
            break;
        case CHOICE_2:
            cout << "Enter the name of the file you want to print: ";
            cin.ignore(100, '\n');
            getline(cin, filenameP, '\n');

            printFile(filenameP, SIZE1, SIZE2);
            break;
        case CHOICE_3:
            cout << "Enter the name of the file you want to sort: ";
            cin.ignore(100, '\n');
            getline(cin, filenameS, '\n');

            sortFile(filenameS, SIZE1, SIZE2);
            break;
        case CHOICE_4:
            break;
        case QUIT_CHOICE:
            cout << "Exiting program." << endl;
            break;
        default:
            cout << "The valid entries are 1-4 or 0 to exit program.";
    }
}

int unsortedFile(string filenameU, int SIZE1, int SIZE2)
{
    long double arr[SIZE1][SIZE2];  //Array for user definition

    ofstream outputFileU;
    outputFileU.open(filenameU.c_str());

    //Get data for file output
    if (outputFileU)
    {
        //Get user input for array
        cout << "Enter numbers into the array." << endl;
        for (int i = 0; i < SIZE1; i++)
        {
            for (int j = 0; j < SIZE2; j++)
            {
                cout << "Enter element [" << i << "] [" << j << "]: ";
                cin >> arr[i][j];

                outputFileU << arr[i][j] << " ";
            }
            outputFileU << endl;
        }
    }
    else
    {
        cout << "File could not be opened for writing..." << endl;
        return 1;
    }

    //Close the file
    outputFileU.close();
    cout << "-------------------------" << endl;
    cout << "File named: " << filenameU << " written." << endl;
    cout << endl;
}

int printFile(string filenameP, int SIZE1, int SIZE2)
{
    ifstream inputFileP;
    inputFileP.open(filenameP.c_str());

    if (inputFileP.is_open())
    {
        long double pArr[SIZE1][SIZE2];
        inputFileP >> SIZE1 >> SIZE2;

        while (inputFileP.good())
        {
            for (int i = 0; i < SIZE1; i++) //steps through rows
            {
                for (int j = 0; j < SIZE2; j++) //steps through columns
                {
                    inputFileP >> pArr[i][j]; //reads data at position i, j
                    cout << pArr[i][j] << " "; //prints value at position i, j
                }
                cout << endl;
            }
        }

        inputFileP.close();
        cout << "-------------------------" << endl;
        cout << "File named: " << filenameP << " printed." << endl;
        cout << endl;
    }
    else
    {
        cout << "File could not be opened for printing..." << endl;
        return 1;
    }
}

int sortFile(string filenameS, int SIZE1, int SIZE2)
{
    int key;

    ifstream inputFileS;
    inputFileS.open(filenameS.c_str());

    if(inputFileS)
    {
        inputFileS >> SIZE1;
        inputFileS >> SIZE2;
        long double temp[SIZE1];
        long double data[SIZE1][SIZE2];

        for (int i = 0; i < SIZE1; i++)
        {
            for (int j = 0; j < SIZE2; j++)
            {
                inputFileS >> data[i][j];
            }
        }

        cout << "Enter which column you want to sort: ";
        cin >> key;
        key--;

        for (int i = 0; i < SIZE1; i++)
        {
            for (int j = 0; j < SIZE2; j++)
            {
                if (data[i][key] > data[j][key])
                {
                    for (int t = 0; t < SIZE1; t++)
                    {
                        temp[t] = data[i][t];
                    }
                    for (int t = 0; t < SIZE1; t++)
                    {
                        data[i][t] = data[j][t];
                    }
                    for (int t = 0; t < SIZE1; t++)
                    {
                        data[j][t] = temp[t];
                    }
                }
            }
        }
        string filenameSOut;
        cout << "\nEnter file name to save sorted data: ";
        cin.ignore(100, '\n');
        getline(cin, filenameSOut, '\n');

        ofstream outputFileS;
        outputFileS.open(filenameSOut.c_str());

        outputFileS << SIZE1 << " " << SIZE2 << endl;

        for (int i = 0; i < SIZE1; i++)
        {
            for (int j = 0; j < SIZE2; j++)
            {
                outputFileS << data[i][j];
            }
            outputFileS << endl;
        }
        outputFileS.close();
        cout << "-------------------------" << endl;
        cout << "File named: " << filenameSOut << " sorted." << endl;
        cout << endl;
    }
    else
    {
        cout << "File could not be opened for sorting...";
        return 1;
    }
}

My output currently reads like so (using some sample inputs):

-------------------------
        MENU
-------------------------
1. Create a custom array file.
2. Print an array from a file.
3. Sort an array from a file.
4. Search an array from a file.
0. Exit program.
-------------------------
Enter your choice from above: 1

Enter the name of the file you want to write: Yeetus

Enter the amount of rows you want in your array between 2 and 10: 3

Enter the amount of columns you want in your array between 2 and 10: 4
Enter numbers into the array.
Enter element [0] [0]: 5
Enter element [0] [1]: 3
Enter element [0] [2]: 8
Enter element [0] [3]: 9
Enter element [1] [0]: 2
Enter element [1] [1]: 1
Enter element [1] [2]: 0
Enter element [1] [3]: 3
Enter element [2] [0]: 5
Enter element [2] [1]: 7
Enter element [2] [2]: 4
Enter element [2] [3]: 4
-------------------------
File named: Yeetus written.

-------------------------
        MENU
-------------------------
1. Create a custom array file.
2. Print an array from a file.
3. Sort an array from a file.
4. Search an array from a file.
0. Exit program.
-------------------------
Enter your choice from above: 2

Enter the name of the file you want to print: Yeetus
8 9 2
1 0 3
5 7 4
4 1.45808e-4950 1.45808e-4950
1.45808e-4950 1.74779e-4944 4.70418e+1991
-------------------------
File named: Yeetus printed.

-------------------------
        MENU
-------------------------
1. Create a custom array file.
2. Print an array from a file.
3. Sort an array from a file.
4. Search an array from a file.
0. Exit program.
-------------------------
Enter your choice from above: 3

Enter the name of the file you want to sort: Yeetus
Enter which column you want to sort: 3

Enter file name to save sorted data: YeetusSorted
-------------------------
File named: YeetusSorted sorted.

-------------------------
        MENU
-------------------------
1. Create a custom array file.
2. Print an array from a file.
3. Sort an array from a file.
4. Search an array from a file.
0. Exit program.
-------------------------
Enter your choice from above: 0

Exiting program.

--------------------------------
Process exited after 58.35 seconds with return value 0
Press any key to continue . . .

The first function unsortedFile works perfectly minus the requirement that it must also include UNSORTED in the first line, followed by ROWS: and COLUMNS: in the second and third line, respectively. With just numbers, it prints like so:

5 3 8 9 
2 1 0 3 
5 7 4 4 

The second function seems to skip the first two numbers in the file, print the rest, then print a bunch of garbage.

The third function gives the following file with the example data I've provided:

5 3
894
103
572
4-2.71616e-11730
1.56264e-48671.68249e-2119-inf

Not...entirely sure why this is happening. If I can get a grasp on reading the data from the file correctly as to get the real numbers, I can finish this program easily with the sorting and searching algorithms (hopefully). For now, I'm stuck. If anyone could help me fix the second and third functions to read/print and sort accurate numbers, as well as let me know how to make the file look like so without it breaking the other functions:

UNSORTED
Rows: 3
Columns: 4
5 3 8 9 
2 1 0 3 
5 7 4 4 

For reference: the class this is for is the introductory course for C++. We are only supposed to use what I've provided here today. Vectors and pointers are also allowed, but I am trying to avoid them as I don't have a full understanding of how to use them, nor do I have time to learn how to use them for this project.

Focusing on printFile for now: The first thing your function does is

inputFileP >> SIZE1 >> SIZE2;

but there are a number of problems:

  • your unsortedFile function does not write this header . You are effectively treating the first two elements of the first row as the sizes to read.
  • it overwrites the SIZE1 and SIZE2 parameters you passed as an argument. Why even pass these if you're going to read them from the file directly?
  • and finally the killer issue: you read the sizes from the file after allocating an array using the SIZE1 and SIZE2 provided as argument.

So you effectively allocate memory for an array of 3x4, and then write into it as if it were a 5x3 matrix. This will give fireworks.

Final note: your top-level menu assumes the user always goes through option 1 to set SIZE1 and SIZE2 . You should either remove these arguments from the functions that do not use them, or explicitly set them. From what I see here it is best if you removed these parameters from the function calls in options 2–4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM