Hey. There is a console application where, for example, the names of people are entered and then saved in a vector. std::vector<std::string> people;std::string name;std::cin >> name;people.push_back(name); The question is how to save this filled vector in the computer’s memory so that when you next open this application, you don’t have to re-fill it?

    3 answers 3

    Save people names to a file on your hard drive.

     using namespace std; int main() { int peopleNumber; string name; ofstream f; //описываСт ΠΏΠΎΡ‚ΠΎΠΊ для записи Π΄Π°Π½Π½Ρ‹Ρ… Π² Ρ„Π°ΠΉΠ» //ΠΎΡ‚ΠΊΡ€Ρ‹Π²Π°Π΅ΠΌ Ρ„Π°ΠΉΠ» Π² Ρ€Π΅ΠΆΠΈΠΌΠ΅ записи, //Ρ€Π΅ΠΆΠΈΠΌ ios::out устанавливаСтся ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ f.open("D:\\names.txt", ios::out); //Π²Π²ΠΎΠ΄ΠΈΠΌ количСство людСй cout<<"People number="; cin>>peopleNumber; //Ρ†ΠΈΠΊΠ» для Π²Π²ΠΎΠ΄Π° ΠΈΠΌΡ‘Π½ ΠΈ записи ΠΈΡ… Π² Ρ„Π°ΠΉΠ» for (int i=0; i<peopleNumber; i++) { cout<<"Name="; cin>>name; //считываСт ΠΈΠ· консоли Π²Π²Π΅Π΄Π΅Π½Π½ΠΎΠ΅ имя f<<name<<"\t"; //запись Π² Ρ„Π°ΠΉΠ» } f.close(); //Π·Π°ΠΊΡ€Ρ‹Ρ‚ΠΈΠ΅ ΠΏΠΎΡ‚ΠΎΠΊΠ° return 0; } 

    Only in your case you need to cycle through the vector, read the names and write to the file.

    • It would be nice to add a check: is the file open? Closing the stream, by the way, is not necessary. It will be closed in the destructor. - ixSci

    You can save the contents of the vector to a file and add a key to specify the data source in the program launch options: file or input in the console.

      Data serialization / deserialization will help you with this task.