+ 1
I have a problem with strings c++
So I got a school project and I have to do an assignment in which I must first enter a number(0>=N<=50000) of strings I will write. For example if I write N=20 I have to write 20 strings. I figured out rest of the project which is to compare each word and find anagrams, but I cannot do anything without that first part. When numbers were in question I used for function and made arrays num[1]=2,num[2]=5,.. but with strings I can only write str[size of string].
2 odpowiedzi
0
If you can make assumptions about the maximum string length, e.g. the entered strings contain at most 31 characters, you can allocate a one-dimensional array of bytes and treat it as an array of such strings, e.g.
size_t n = ... // input
char* arr = new char[ n * 32 ]{};
Instead of indexing 0, 1, 2, ... the strings would then be layed out according to the constant, e.g. arr[ 0 ] is the first string, arr[ 32 ] the second, and so on.
Otherwise, you would need to allocate each string on its own once more, i.e.
char** arr = new char*[ n ]{};
for ( size_t i = 0; i < n; ++i )
{
arr[ i ] = new char[ ... ]{};
}
This could be simplified by using C++ strings instead of C strings (std::string) to represent the strings, and further by using std::vector<> as a container to store the strings. Both containers already automatically manage their resources for you.
std::vector< std::string > arr( n );
for ( size_t i = 0; i < n; ++i )
{
// read string
std::cin >> arr[ i ];
}