dev
dev

Reputation: 121

an unwanted empty line is printed. can someone help me to remove it?

as visible in the output images attached, an unwanted line is printed. if someone can help me with removing it, I would be really thankful:) thanks in advance.

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    
    int a, b;
    
    cin>>a;
    cout<<endl;
    cin>>b;
    
    for (int i=a; i<=b; i++) {
        if (i==1) {
            cout<<"one"<<endl;
            
        }
        
        else if (i==2) {
            cout<<"two"<<endl;
            
        }
        
        else if (i==3) {
            cout<<"three"<<endl;
            
        }
        
        else if (i==4) {
            cout<<"four"<<endl;
            
        }
        
        else if (i==5) {
            cout<<"five"<<endl;
            
        }
        
        else if (i==6) {
            cout<<"six"<<endl;
            
        }
        
        else if (i==7) {
            cout<<"seven"<<endl;
            
        }
        
        else if (i==8) {
            cout<<"eight"<<endl;
            
        }
        
        else if (i==9) {
            cout<<"nine"<<endl;
            
        }
        
        else {
            if (i%2==0) {
                cout<<"even"<<endl;
            } else {
                cout<<"odd"<<endl;
            }
            
        }
    } 
    
    
    
    
    return 0;
}

input

expected output

actual output

actually this is a question on Hackerrank. I checked for the solution online, it exactly matches with my code. so I am not able to find the error in this code.

Upvotes: 0

Views: 64

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 118097

You explicitly print the empty line between reading a and b:

    cin>>a;
    cout<<endl;  // here
    cin>>b;

Just remove that line:

    cin>>a;
    cin>>b;

or better, read both and make sure that reading succeeded before continuing:

    if(not (std::cin >> a >> b)) return 1;

Upvotes: 5

Related Questions