0

I have no idea why does compiler "skip" the second word like if I set ile to 1, I input the first sentence and it automatically skips the second one, but if I set ile to any other >1, I can input both of words.

The task is to check whether words are palindromes to each other. I tried to replace it with looped getchar but worked the same way as below.

My code:

#include <iostream>
#include <string.h>

using namespace std;

void qsort(char tab[], int min, int max)
{
    if(min<max)
    {
        int min_min = min;
        for(int i=min+1;i<=max;i++)
        {
            if(tab[i]<tab[min])
            {
                swap(tab[++min_min],tab[i]);
            }
        }
        swap(tab[min],tab[min_min]);
        qsort(tab,min,min_min-1);
        qsort(tab,min_min+1,max);
    }
}
bool sprawdz(char tab[],char tab2[])
{
    for(int i=0;i<strlen(tab);i++)
    {
        if(tab[i]!=tab2[i])
        {
            return false;
            break;
        }
    }
    return true;
}

int main()
{
    char tablica1[100];
    char tablica2[100];
    int ile;
    cin>>ile;
    for(int i=0;i<ile;i++)
    {
        cin.getline(tablica1, 100);
        cin.getline(tablica2, 100);
        qsort(tablica1,0,strlen(tablica1)-1);
        qsort(tablica2,0,strlen(tablica2)-1);
        cout<<tablica1<<endl<<tablica2;
        if(sprawdz(tablica1,tablica2))
        {
            cout<<"TAK";
        }
        else
        {
            cout<<"NIE";
        }

    }

    return 0;
}
Waqar
  • 8,558
  • 4
  • 35
  • 43

1 Answers1

1

Change this:

cin.getline(tablica1, 100);
cin.getline(tablica2, 100);

To:

cin.getline(tablica1, 100);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.getline(tablica2, 100);

The reason is that cin leaves a newline in the input stream. You have to use cin.ignore() to remove it.

Also, you need to #include <limits> for numeric_limits.

Refer to this answer for a deeper understanding: Why won't getline function work multiple times in a for loop with an array of structures?

Waqar
  • 8,558
  • 4
  • 35
  • 43