user5733274
user5733274

Reputation:

How can I enter strings of different length in a 2d char array in C++?

I am required to enter 4 strings therefore number of strings that needs to be entered is specified but the length of each string is different. Since I have to perform character specific operations it has to be 2d char array, if I am not wrong. How can i code this in c++.

Reference: the question is in spoj

Input:

4          // number of test cases
your 
progress 
is 
noticeable

How to input this in C++ ? Kindly help in clearing the concept behind this.

Upvotes: 0

Views: 702

Answers (2)

Z Rev
Z Rev

Reputation: 84

If you really wanted to, you could use malloc() to initialize a character array and then realloc() sizeof(char) times x amount of characters. You could even add a marker to separate the various lines you want to enter.

Just make sure you don't forget to free() the array at the end of your code.

Upvotes: 0

cadaniluk
cadaniluk

Reputation: 15229

The C++ standard library provides the class std::string, which you should opt for as opposed to char*, char[], and that C-ish, unsafe stuff.

You then read into these strings (in your case) from the std::cin input stream using either std::istream::operator>> or std::getline or whatever you want to use, depending on what you want to read.

Now, to store these strings in a suitable data structure, something array-ish seems fit. The C++ standard library offers various kinds of containers for this, solely depending on how you want to store/access the strings. Examples are std::vector (dynamically modifiable array), std::array (safer alternative to an array), std::deque (double-ended queue), std::forward_list (singly-linked list), and std::list (doubly-linked list). These data structures provide appropriate operations to append items, remove them, insert them, etc. depending on the particular container how efficient they are and if they're implemented at all.
For general-purpose tasks, I recommend std::vector.

Upvotes: 3

Related Questions