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
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.
|