-1
$\begingroup$

i spent literally 5hrs trying to figure out, why the value of n is 1 for my second test case ( which begins at line 12 ) , but i am unable to, could you help me with that?

    int t,n,i,j;
    char c;
    cin>>t;
    while(t--)
    {
        cin>>n;
        cout<<n<<"\n";
        getchar();
        while(scanf("%c %d %d\n",&c,&i,&j)==3)
        {
            cout<<c<<" "<<i<<" "<<j<<"\n";
        }
        getchar();
    }

test case:- first line represents the number of test cases, and each test case has a blank line.

2

10
c 1 5
c 2 7
q 7 1
c 3 9
q 9 6
c 2 5
q 7 5

2
q 1 1
c 1 1
q 1 1

output :-

10
c 1 5
c 2 7
q 7 1
c 3 9
q 9 6
c 2 5
q 7 5
1

```
$\endgroup$
0
$\begingroup$

Your code probably fails because of your use of scanf(...) == 3, or because of your use of getchar().

Consider this alternative instead:

#include <iostream>

int main() {
  int num_tests;
  std::cin >> num_tests;

  for (int k = 0; k < num_tests; ++k) {
    int n;
    std::cin >> n;
    std::cout << n << "\n";

    std::cin.ignore(1, '\n');

    std::string buf;
    while (getline(std::cin, buf)) {
      if (buf.empty())
        break;

      char c;
      int i, j;
      sscanf(buf.c_str(), "%c %d %d\n", &c, &i, &j);
      std::cout << c << " " << i << " " << j << "\n";
    }
  }
}

For clarity, prefer naming your variables in a clearer way and using for loops. Also, never use the identifiers i or j for anything other than looping.

| cite | improve this answer | |
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.