简体   繁体   中英

read text file and store into array

I have a .txt file that contains in which the content of an array is written. But if the program closes, the array's content is of course deleted, because of which I need to read the .txt file to "remind" the array of its previous content.

That's my code:

#include <fstream>

unsigned short int highscores[11]{0};

int main()
{
    highscores[0] = score;
    std::sort(highscores, highscores + 11);
    std::ofstream outputFile("scores.txt", std::ios::trunc);
    for (short int i = 10; i > 0; i--) {
        outputFile << highscores[i] << std::endl;
    }
    outputFile.close();
}

and that's my scores.txt file:

22
15
13
10
5
5
3
1
1
1

Any recommendations to this code are also welcome!

You are only writing in a file and not reading. If you close your program and start it again your array will be empty like you said. So if you want to read the files from the file you have written in you have to use

std::ifstream inputFile("scores.txt",std::ios::in);

Then there are many ways how to read the file. One would be to declare a string:

std::string line;

then using a while loop and getline.

usigned short int highscores[11]{0}; int i=0; while(getline(inputFile,line) { highscores[i]=stoi(line); // stoi means string to int. We use that because line is a string but we need the numbers

}

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