Hello, I implement my class String and create my class `City.

 include <iostream> #include <string> #include "String.h" #include <fstream> #include <vector> #define string String #define END std::endl class City { private: string Name; int Ppl; double Area; int Birth; int Schools; public: City(); ~City(); void showInfo(); void getData(); void write(char *fileName); void read(char *fileName); }; 

I need to write my information to a binary file. To do this, I implement the two methods write and read , in which one argument comes the name of the file, since my program works with arguments, one of them I give the name of the file.

My problem is this:

My methods use such functions that cannot work with my String . This is s_str, size (). Could you help me with the implementation of these functions?

 #include "City.h" #include "String.h" #include "TCharArray.h" #include <iostream> #include <fstream> #include <io.h> #include <vector> City::City() : Name("NoName"), Ppl(0), Area(0.0), Birth(0), Schools(0) {} City::~City() { } void City::showInfo() { std::cout << "Name\t\t" << "People\t\t" << "Area\t\t" << "Birth\t\t" << "Schools\t\t" << END; std::cout <<""<<Name<<"\t\t" << Ppl<<"\t\t" << Area<<"\t\t" << Birth<<"\t\t" << Schools<< END; } void City::getData() { std::cout << "Enter a name of the city: "; (std::cin >> Name).get(); std::cout << "Enter quanity of people in the city: "; std::cin >> Ppl; std::cout << "Enter area of the city: "; std::cin >> Area; std::cout << "Enter a year of foundation of the city: "; std::cin >> Birth; std::cout << "Enter quanity of schools in the city: "; std::cin >> Schools; } void write(char *fileName) { std::vector<string>words; std::fstream tab(fileName, std::ios::binary | std::ios::out); for (size_t i = 0; i < words.size(); i++)// size() Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ с ΠΌΠΎΠΈΠΌ String { size_t size = words[i].size();// size() Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ с ΠΌΠΎΠΈΠΌ String // пишСм Π² Ρ„Π°ΠΉΠ» Π΄Π»ΠΈΠ½Ρƒ строки: tab.write((char *)&size, sizeof(size)); // Ρ‚Π΅ΠΏΠ΅Ρ€ΡŒ саму строку: tab.write(words[i].c_str(), size);// с_str Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ с ΠΌΠΎΠΈΠΌ String } tab.close(); } void read(char *fileName) { std::vector<string>words; std::fstream show(fileName, std::ios::binary | std::ios::in); for (size_t i = 0; i < words.size(); i++)// size() Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ с ΠΌΠΎΠΈΠΌ String { size_t size; // Ρ‡ΠΈΡ‚Π°Π΅ΠΌ Π΄Π»ΠΈΠ½Ρƒ ΠΎΡ‡Π΅Ρ€Π΅Π΄Π½ΠΎΠΉ строки: show.read((char *)&size, sizeof(size)); // Ρ‡ΠΈΡ‚Π°Π΅ΠΌ саму строку: char buf[size + 1]; show.read(buf, size); buf[size] = 0; } show.close(); } 

    1 answer 1

    Well, you have used

     vector<string> words -> words.size() == 0 

    And the implementation is normal

     size_t size() const noexcept { return len; } const char* c_str() const noexcept { return data; } 

    link to your implementation of string (if necessary): https://github.com/leprik0n/str