1

When i try to run my cpp code with multiple testcases on ubuntu then i get unexpected results. It works fine when i run testcases one by one but when i copy and paste testcases then terminal gives unexpected line breaks

For example

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

int main(){
    int t;
    cin>>t;
    while(t--){
    int n;
    cin>>n;
    cout<<n<<"Hello"<<endl;
    }
}

when i run this code with testcase 5 4 3 2 1 5

by directly copying and pasting i get following result

5
4
3
2
1
5 4Hello
3Hello
2Hello
1Hello

5Hello

instead of

5
4
3
2
1
5 
4Hello
3Hello
2Hello
1Hello
5Hello

can anyone tell whats the problem i have tried for many hours researching but i am not getting any solution. I have tried konsole,xterm,gnome terminal all are giving same results on directly doing copy paste of testcases.

Muskan Arora
  • 56
  • 11
Abhishek
  • 46
  • 1
  • 6

1 Answers1

0

Just paste

5
4
3
2
1
5

instead of

5
4
3
2
1
5

The issue is happening because when you are using the second case the following happens -

  1. First 5 is read and with the '\n' character, the cin knows that the read is complete. Thus 5 is assigned to t.
  2. In the loop all the integers are read till 1, and 5 is not read, because it's not being followed by the '\n' character. Thus you have the 4 outputs on the terminal -
 4Hello
3Hello
2Hello
1Hello

and after pressing the enter key, the '\n' character is fed to the input and then 5 is read and 5Hello is printed.

If we use the first case, then the output comes as desired, because every integer is followed by the '\n' charcater.

imperial-lord
  • 601
  • 8
  • 20
  • This didn't worked. Actually the same problem came. What i did is manually give t and then pasted rest things but then also there were extra line breaks for last output. – Abhishek Jan 08 '21 at 18:58