Search code examples
c++getlinepalindromestdstring

Output Befor giving the input of string for finding palindrome


This code is giving output YES just after entering the value of test case. Code: for alphanumeric pallindrome

int main() {
    int t;
    cin>>t;
    while(t--){
        string s;
        int count = 0,size = 0;
        getline(cin,s);
        cout<<s<<endl;
        s.erase(remove_if(s.begin(),s.end(),not1(ptr_fun((int(*)(int))isalnum))), s.end());
        for(int i=0;i<=s.size()/2;i++){
            size++;
            if(tolower(s[i])==tolower(s[s.size()-i-1])){
                count++;
            }
            else
                break;
        }
        if (count==size)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
    return 0;
}

Output I am getting is YES without giving any input of string

For Input:
2
I am :IronnorI Ma, i
Ab?/Ba
Your Output is:

YES
I am :IronnorI Ma, i
YES

Solution

  • This code is giving output YES just after entering the value of test case. Output I am getting is YES without giving any input of string

    Your problem is here:

    /* code */
        cin>>t;    -----------> std::cin        
        while(t--)
        {
            string s;
            int count = 0,size = 0;
            getline(cin,s); ------------> std::getline()
    
    /* remaining code */
    

    Reading with something like std::cin leaves the newline in the input stream. When the flow of control reaches std::getline(), the newline will be discarded, but the input will cease immediately. This leads, std::getline()s attempt read a new line and skips the input.

    FIX: When switching from white space delimited to newline delimited input, you want to clean all newlines from the input stream by doing a std::cin.ignore()

    The fixed code should be: https://www.ideone.com/ucDa7i#stdin

    #include <iostream>
    #include <string>
    #include <limits>
    #include <algorithm>
    
    int main()
    {
        int t;
        std::cin >> t;
        // fix
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
        while(t--)
        {
            std::string s;
            int count = 0,size = 0;
            getline(std::cin,s);
            /* remaining code */
    }