This code:
int T;
// ...
cin>>T;
...reads an int
from standard input. To get it to read that int
, you need to press the enter key, but this code does not remove that enter from the input buffer. Then...
cin.getline(J,100);
This tries to read a string from the input buffer, up to the first new-line character. It removes that new-line from the input buffer, but does not include it as part of the string. As such, if you don't look really closely, it appears to do essentially nothing -- i.e., you end up with an empty string.
You generally want to stick to either field-oriented input (like your cin >> T;
or else line-oriented input (getline
). Mixing the two, however, can be a bit tricky, especially if the getline
comes after the field-oriented input. Don't get me wrong: it can work -- and work perfectly well at that, but you need to know what you're doing, and even then it can still surprise you now and again.
As noted in my comment (and @johnathon's answer) you also generally want to use std::getline
to read an std::string
, instead of std::cin.getline
with an array of char. The latter is clumsy to deal with, even at best.
My own preference is (as a rule) to use line-oriented input throughout if you're going to use it anywhere.
std::string temp;
std::getline(std::cin, temp);
int T = lexical_cast<int>(temp);
while (T--) {
std::string j;
std::getline(std::cin, j);
// ...
As an aside, I'd also avoid using T
as a name of an ordinary variable in C++. It's quite commonly used as the name of a template parameter; using it for "normal" variables is more likely to lead to confusion, especially for more advanced programmers who use templates more often.