You are reading n
strings, but the first one doesn't contain what you expect.
When you write input in the console, you write something like:
3\nstring1\nstring2
, where \n
is the newline character (when you press Enter).
When you do cin >> n
, you parse this input string, and you get the integer. Meaning that you remain with
\nstring1\nstring2
in the buffer. And when you do a getline
, you parse everything up to the first newline (including the newline). That's why you get the first string empty.
A quick and dirty fix is to read the newline too:
int n;
char newline;
cin >> n >> newline;
, and then loop as you do now.
Some remarks about your code.
string arr[n]
is not valid C++. In C++, there is no official support for arrays with variable size like this (some compilers support it, but this doesn't mean it's standard). You should use a std::vector
:
std::vector<std::string> arr(n);
(the rest of the code remains the same). An even better way would be to declare it empty, and then use push_back
to populate it.
Also, when comparing j < arr[i].length()
, you are comparing a variable of type int
with a variable of type size_t
, which might be bigger than an int
and create issues for very long strings. Use size_t
as the type for j.