0

I have the following C++ code-

#include <iostream>
#include <set>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
    int t;
    cin>>t;
    string text;
    string text2;
    int len1, len2,len3;
    while(t--) {

        getline(cin,text); //first string input
        set<char> s(text.begin(),text.end());
        len1=s.size();

        getline(cin,text2); //second string input
        set<char> s2(text2.begin(),text2.end());
        len2=s2.size();
        len3=len1+len2;
        s.insert(s2.begin(),s2.end());
        len1=s.size();
        if(len1<len3){
            cout << "YES" << endl;
        } else {
            cout << "NO" << endl;
        }

    }
    return 0;
}

When I'm running this program it seems that the first string input is not being taken properly. The second input is working fine. The program is only taking input of t and text2, but not text1. What's the problem actually?

Note: The program is working as expected when I remove the loop.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Abdullah Shahriar
  • 355
  • 1
  • 3
  • 15

1 Answers1

1

You are mixing the use of cin >> and getline. I suggest using getline for all interactive user input.

To read an int using getline without error checking, you can do something like:

string line;
getline(cin, line);
int t = stoi(line);

The problem is that when cin >> t reads an integer, it reads only the integer and leaves the next character (a newline) in the input buffer. This newline is read by the next call to getline, which leads to confusion about the operation of your program.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285