Reading T won’t read the rest of the line after T, so the next call to getline will read the remaining characters after T until the end of the line.
You need to skip the rest of the line after reading T:
int T;
cin>>T;
// Skip to the next line.
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
After that, you’ll need to fix the potential out-of-bounds access on the line:
else if (str[len-1]=='t' && str[len-2]== 'o' && str[len-3]== 'n' && str[len-4]== ' '){