0

I wrote a code to find the substring from of a string from after "I have a " which is specifically nine characters. It gives the correct output on the first input but misses the first character on the second. Can anyone please tell me why ??

#include<bits/stdc++.h>
using namespace std;

int main()
    {
    int t;
    cin>>t;
    while(t--)
    {
        cin.ignore();
        string s1;
        getline(cin,s1);
        
        string s2;
        getline(cin,s2);
        
        int n1=s1.length();
        int n2=s2.length();
        
        string itema,itemb;
        itema=s1.substr(9,n1);
        cout<<itema<<endl;
        itemb=s2.substr(9,n2);
        cout<<itemb<<endl;
        cout<<"Uh! "<<itemb<<"-"<<itema<<"!"<<endl;
    }

    return 0;
    }

enter image description here

  • `cin.ignore()` eats the first character of the first line of input, the second time through the loop. – Igor Tandetnik Aug 15 '20 at 14:44
  • 5
    Couple of pointers here: prefer `using` to `#define`, you don't need the c headers ending with .h, the `using namespace std;` is best avoided, and so is `#include`. Avoid aliases for built in types such as `#define ll long long int`, they introduce confusion. – Ron Aug 15 '20 at 14:45
  • Mixing `getline` and `>>` can be tricky. Also, your code doesn't check for input failure, so if/when input failure occurs it might do unexpected things. – Eljay Aug 15 '20 at 14:48
  • [Why should I not #include ?](https://stackoverflow.com/q/31816095/5910058) – Jesper Juhl Aug 15 '20 at 15:31
  • [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/5910058) – Jesper Juhl Aug 15 '20 at 15:32

0 Answers0