0

I'am a beginner in c++. I'am trying to write a file which accepts input and output using cout.
The code:

#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int main()
{

    int t;//No. of testcases

    cin>>t;
    while(t--)
    {
        int n;//number of pairs
        cin>>n;
        cout<<"n="<<n<<"\n";

        int a;//number
        char b;//character
        for(int i=0;i<n;i++){
        cin>>b>>a;
        cout<<b<<" "<<a<<"\n";}

    }
    return 0;
}

The input:
2
42
A 3
A 3
A 3
A 3
A 12
A 12
A 12
A 12
A 6
A 6
A 9
B 3
B 3
B 3
B 3
B 12
B 12
B 12
B 12
B 6
B 6
B 6
B 9
B 9
B 9
C 3
C 3
C 3
C 3
C 6
C 6
C 9
C 9
C 12
C 12
C 12
C 12
D 3
D 6
D 6
D 9
D 9
D 12
42
A 3
A 3
A 3
A 3
A 12
A 12
A 12
A 12
A 6
A 6
A 9
B 3
B 3
B 3
B 3
B 12
B 12
B 12
B 12
B 6
B 6
B 6
B 9
B 9
B 9
C 3
C 3
C 3
C 3
C 6
C 6
C 9
C 9
C 12
C 12
C 12
C 12
D 3
D 6
D 6
D 9
D 9
D 12

The ouptut I want:

n=42
A 3
A 3
A 3
A 3
A 12
A 12
A 12
A 12
A 6
A 6
A 9
B 3
B 3
B 3
B 3
B 12
B 12
B 12
B 12
B 6
B 6
B 6
B 9
B 9
B 9
C 3
C 3
C 3
C 3
C 6
C 6
C 9
C 9
C 12
C 12
C 12
C 12
D 3
D 6
D 6
D 9
D 9
D 12
n=42
A 3
A 3
A 3
A 3
A 12
A 12
A 12
A 12
A 6
A 6
A 9
B 3
B 3
B 3
B 3
B 12
B 12
B 12
B 12
B 6
B 6
B 6
B 9
B 9
B 9
C 3
C 3
C 3
C 3
C 6
C 6
C 9
C 9
C 12
C 12
C 12
C 12
D 3
D 6
D 6
D 9
D 9
D 12

The output I get: n=42
A 3
A 3
A 3
A 3
A 12
A 12
A 12
A 12
A 6
A 6
A 9
B 3
B 3
B 3
B 3
B 12
B 12
B 12
B 12
B 6
B 6
B 6
B 9
B 9
B 9
C 3
C 3
C 3
C 3
C 6
C 6
C 9
C 9
C 12
C 12
C 12
C 12
D 3
D 6
D 6
D 9
D 9
D 12
n=0

Why is this happening? It works for small inputs but when I directly type it in but does not accept any input when I copy the same. Is this a problem with online compilers or do I need to clear cin in some way for it to accept input. Any help would be appreciated.
Edit:I needed to use cin.ignore()

  • 1
    Fantastic. You gave us code, the input and the expected output. Only thing more I could ask for is that you run the program in the debugger that came with your development tools and step through the program looking for where the program begins to deviate from the expected. Find that and you've found the bug yourself. Well, one bug, at least. – user4581301 Feb 09 '20 at 18:38
  • 4
    Side note: You owe it to yourself to read up on [what `#include` does](https://stackoverflow.com/questions/25311011/how-does-include-bits-stdc-h-work-in-c) and [why you shouldn't use it](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). – user4581301 Feb 09 '20 at 18:40
  • Thank You I needed to use cin.ignore() – Saketh ajith Feb 16 '20 at 14:32

0 Answers0