Please tell me how to implement an array of null-terminated strings? I implemented a string read:

char* get_string(){ constexpr std::size_t initial_size = 4; char* buf = new char[initial_size]; std::size_t used = 0,allocated = initial_size; std::cin >> std::noskipws; char c; while((std::cin >> c) && c!='.'){ if(used+2 > allocated){ allocated = allocated*3/2; char* new_buf = new char[allocated]; for(std::size_t i = 0; i<used;++i) new_buf[i] = buf[i]; delete[] buf; buf = new_buf; } buf[used++] = c; } std::cin >> std::skipws; if(!std::cin){ delete[] buf; buf = nullptr; }else{ ++used; buf[used-1] = '.'; buf[used] = '\0'; } return buf; } 

The task is to organize an array in which to write such strings.

Closed due to the fact that the essence of the question is not clear to the participants by Vlad from Moscow , αλΡχολυτ , Vladimir Martyanov , D-side , Harry Nov 29 '16 at 17:44 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    The essence of the question is not clear. What problems do you have with this? - Vlad from Moscow

1 answer 1

Array of 3 lines

 char *a[] = {(char *)"str1", (char *)"str2", (char *)"str3"}; // Π² Π‘ ΠΌΠΎΠΆΠ½ΠΎ ΠΎΠΏΡƒΡΡ‚ΠΈΡ‚ΡŒ ΠΏΡ€ΠΈΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ Ρ‚ΠΈΠΏΠ° `(char *)` 

or

 const char *a[] = {"str1", "str2", "str3"}; #define ASIZE(x) (sizeof(x) / sizeof((x)[0])) // макрос для количСства элСмСнтов Π² Ρ‚Π°ΠΊΠΎΠΌ массивС 

In your case (after the appearance of the sample code), you can either make a dynamic array char **da , which should be supplemented with new elements (pointers that get_string() returns) in exactly the same way as you build a string in your function, or use the ready-made vector .

 #include <vector> .... vector<char *> v; // Π²Π΅ΠΊΡ‚ΠΎΡ€ ΡƒΠΊΠ°Π·Π°Ρ‚Π΅Π»Π΅ΠΉ char *s; while (s = get_string()) v.push_back(s); // Π΄ΠΎΠ±Π°Π²ΠΈΠΌ Π½ΠΎΠ²ΡƒΡŽ строку Π² ΠΊΠΎΠ½Π΅Ρ† Π²Π΅ΠΊΡ‚ΠΎΡ€Π° // распСчатаСм всС строки for (int i = 0; i < v.size(); i++) cout << v[i] << '\n';