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.

I get logical errors from a program that would output the last condition even if it satisfies other conditions.

+2 votes
asked Oct 4, 2022 by Abdul Hamid Mangorangca (140 points)

I am creating a simple c++ program that would output "Hello there" if a user enters "Hi there", and vice versa, "Hi there" if a user enters "Hello there".

I did two different programs trying to do this function because the first one, I got a logical error, and the same for the second one. The logical error is that it outputs "Good bye!", the last condition, even if I have put a greeting that satisfies the first or second condition.

I am stuck, please help. Sorry for the formatting of question since I don't know how to describe the question.

The link to screenshots of the two programs's codes:

https://imgur.com/a/SenIVUv

1 Answer

0 votes
answered Oct 7, 2022 by Peter Minarik (88,520 points)

In your code you're reading from the standard input twice. The first, you read just one word (one token until a white space character), then you read the whole line after the first token:

cin >> greetings;
getline(cin, greetings);

because of this, you always ignore the first token and only store anything following that in greetings.

To fix this, remove the first line above.

It is also a good practice, if you do not know what your code is doing, to start printing some debug messages. In your case, it would make sense to print the value of the greetings variable to see what's inside, and why your desired behaviour is not working.

std::cout << greetings << std::endl;

Since you did not share your program, just a screenshot, I can only do a theoretical analysis. It would make things much easier if you'd share your code so one can run it as well and ensure the proposed fix really works. :)

I hope this helps. Good luck! :)

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.
...