简体   繁体   中英

Issue with reading in integers from a text file into an array

I am working on a movie database that lets users input movies with Title, Director, and Release Year. The database then saves all 3 of the inputs as 2 strings(Title and Director) and 1 int value(RY) for release year and stores all of them together into 1 text file. However, I want to sort the movies from newest year to oldest year but when we want to read in the integer from a text file into an array the sort method doesn't do anything besides print out the movies in the same order the user inputs them. Is there any way of putting integers from the text file into the array together? Below is the sort method. The amount of movies we want in the database is 7.

void sort()
{
    string Title;
    string fileName;
    string Director;
    int RY;

    int array [7] = { };
    int temp;
    int p;

    fstream file("directory.txt");

    for(int i = 0; i < 7; ++i)
    {
        file >> array[i];
    }

    for (int i = 1; i < sizeof(array); i++) {
    temp = array[i]; //temp = 3
    p = i -1; // p = 1
    while( p >=0 && array[p] > temp){
        array [p + 1] = array [p];
        p = p-1; //p = 0
    }
    array [p + 1] = temp;
}


        for (int i = 7 - 1; i >= 0; i--)
            cout << array[i];

        cout << "Entire Movie database" << endl;
        cout << "------------------------" << endl;
        ifstream dir("directory.txt");
        while (dir >> Title >> Director >> RY){
            cout << Title << ' ' << Director << ' ' << RY << endl;
        }

        main();
    }

Your custom sorting procedure (probably) does whatever it should do: it sorts integers in your array . The following code just reads the contents of your file and outputs in the order it reads:

    ifstream dir("directory.txt");
    while (dir >> Title >> Director >> RY){
        cout << Title << ' ' << Director << ' ' << RY << endl;
    }

I wonder how you expect to read 7 integers from the file for the first time and read all the four fields for the second. Maybe you think that the string values would be skipped? They wouldn't

There are other problems in your code. For example, sizeof(array) doesn't return the number of elements but the size in bytes. One more thing: why are you calling main from your sort function?

Why are you reinventing the wheel? Read the values into a struct, store them in a vector, then use the std::sort procedure.

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