Why isn’t my C++ code’s if statement working properly?

0
8
Asked By CuriousCoder88 On

I'm having some trouble with my C++ code where it seems like one of my if statements is being ignored, but I'm not getting any error messages. The program runs fine in the terminal, but when I test it, the first if statement doesn't seem to execute as expected. I suspect the issue might be related to the last if statement or the else if statements that follow, but since I'm new to C++, I'm not sure how to fix it. Here's the code I'm working with:

```cpp
double score;
char LetterGrade;

cout <> score;

cout <> LetterGrade;

if ( ! ( score > 0 && score < 100) )
{
cout << "Invalid Score";
return 0;
}
if (! (LetterGrade =='A' || LetterGrade == 'B' || LetterGrade == 'C' || LetterGrade == 'D' || LetterGrade == 'F' ) )
{
cout << "Invalid letter grade";
return 0;
}

if ( score < 60)
cout <= 60 && score <=69)
cout <=70 && score <= 79)
cout <=80 && score <= 89)
cout <=90 && score <= 100)
cout << "Excellent Job! A";
```

3 Answers

Answered By DebuggingDynamo On

Also, a great way to troubleshoot is by adding some debug print statements to check the values before they're used. Like, print out the score value after you get it from input to make sure it's what you expect! That might give you more clues about what’s going wrong.

Answered By TechieTurtle42 On

It sounds like your output isn’t appearing right away. In C++, sometimes you need to flush the output stream to make sure your messages show up before getting input. You can use `std::endl` or `std::flush`. Just modify your cout statements like this: `cout << "Enter your homework score: " << std::flush;` This should help!

Answered By CodeExplorer77 On

Make sure you're flushing the output whenever you switch from `std::cout` to `std::cin`. Here's how you can modify your code: `cout << "Enter your homework score: " <> score;` and do the same for the letter grade. This way, it should display the message before waiting for input!

NerdyNovice -

Yeah, that's a common misconception! Just remember, `std::cout` doesn’t guarantee the output will appear before the next input. Forcing it with a flush is definitely the way to go.

DebuggingDynamo -

Exactly! It’s not always intuitive, so worth double-checking your output every time you switch types.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.