Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Need help finding the newline in this program

+3 votes
asked Mar 4, 2023 by Justin Jones (150 points)
Trying to turn in work for class but it says that there's a newline after the output. Making the output wrong. Can someone help me find this issue? I'm new to programming and C++.

#include <iostream>
using namespace std;

int main()
{
    int speedLimit, drivingSpeed;
    cin>>speedLimit>>drivingSpeed;  
    if((drivingSpeed-speedLimit) < -10)
        cout<< 50;
    else if(((drivingSpeed-speedLimit) >= 6) & ((drivingSpeed-speedLimit) <= 20))
        cout<< 75;
    else if(((drivingSpeed-speedLimit) >= 21) & ((drivingSpeed-speedLimit) <= 40))
        cout<< 150;
    else if((drivingSpeed-speedLimit) >= 40)
        cout<< 300;
    else    
        cout<< 0;
    return 0;
}

1 Answer

+1 vote
answered Mar 5, 2023 by Peter Minarik (86,040 points)

... there's a newline after the output.

I'd advise reviewing the error message as what your's saying is impossible. The last thing you print to the standard output is a number (50 or 75 or 150 or 300 or 0). It is not followed by anything, definitely not a new line.

You can easily verify this by adding an std::cout << "Hello" << std::endl; before the return 0; statement and see that "Hello" is on the same line as your printed number, not on a new line.

Maybe the error message says that you're supposed to have a new line but you don't have one.

I'm not sure about the logic of how these numbers (0, 50, 75, 150, 300 are determined -- maybe they come from the task description). However, your line else if((drivingSpeed-speedLimit) >= 40) has 40 inclusive, while it's also checked in the previous line of code, so actually your last else if will print 300 starting from 41, not 40. Is this what you wanted to do?

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...