0

Here t is the variable I'm taking the number of test cases as input. When entering 1, it is just printing a new line and terminating. When giving a number more than 1, it is printing a new line then asking for new input. Can someone tell me why ??

#include "iostream"
#include "string"

using namespace std;

int main()
{
    int t,i,k,l,j=0;
    char c;
    string s, s2;
    cin >> t;
    while(t>0)
    {
        cout << "Enter Name - " << endl;
        getline (cin,s);
        l = s.size();
        s2 = toupper(s[0]);
        for(i=1; i<l; i++)
        {
            if(s[i] == ' ')
            {
                c = toupper(s[i+1]);
                s2 = s2 + ". " + c;
                j = i;
            }
            if(i == l-1)
            {
                if(j!=0)
                {
                    for(k=j+2; k<l; k++)
                    {
                        c = tolower(s[k]);
                        s2 = s2 + c;
                    }
                }
                else
                {
                    for(k=1; k<l; k++)
                    {
                        c = tolower(s[k]);
                        s2 = s2 + c;
                    }
                }
            }
        }
        cout << s2 << endl;
        s2 = ""; j=0; t--;
    }
    return 0;
}

Output -

puku@puku-mint /media/puku/Data/Work/Programs/C++ Mine/CodeChef/Easy $ ./a.out
1
Enter Name - 

puku@puku-mint /media/puku/Data/Work/Programs/C++ Mine/CodeChef/Easy $ ./a.out
3
Enter Name - 

Enter Name - 
my name
M. Name
Enter Name - 
this is name
T. I. Name
daddyodevil
  • 175
  • 1
  • 11
  • One solution would be to add the line `while (cin.peek() == '\n') cin.get();` before the call to `getline()`. This clears the newline character out of the input stream. – jodag Jul 26 '17 at 19:53

1 Answers1

2

You type 1<enter>. cin >> t just consumes the 1. The <enter> is then consumed by getline(cin,s).

Mark Tolonen
  • 132,868
  • 21
  • 152
  • 208