简体   繁体   中英

Running on ubuntu terminal giving unexpected line breaks

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM