Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C++ Trying to solve a slight issue with my simple code.

Mdscommand

New Coder
#include <iostream>
#include <string>
using namespace std;

int main()
{
bool complete = false;
char user;
bool input = false;
while (complete == false)
{
cout << "are you new to c++? (y/n)" << endl;
cin >> user;
switch (user)
{
case 'y':
cout << " welcome new programmer!" << endl;
complete = true;
break;

case 'n':
cout << "welcome back to c++!" << endl;
complete = true;
break;

default:
cout << "invalid reaponse. please try again." << endl;
break;
}
}
return 0;
}


So the code works perfectly. If the user gives correct input it runs as expected. If the user gives incorrect input, it responds "invalid input" and runs the loop again. The code also works perfectly if the user inputs the full word yes or no. The issue arises when the user inputs some like "I am not". In that case the loop checks each individual character until it hits the 'n' in the phrase and then runs that case. I've tried a few different approaches to solve it but can't come to a resolution.
 
The problem is that you use a 1-character input buffer for user input. Being a C programmer I would expect this to crash when a user types more than one character, but apparently C++ just takes the first character (which is what you want) and dumps you back in the input loop with the remaining characters (which is what you don't want). The customary way to ask user input, in any compiled language, is to use a string buffer of sufficient cq. reasonable length. In this case, that length could be one, but maybe you'll want to allow other input. I can't readily tell you to do that in C++ (I stay clear of it as much as I can) but I guess it's an easy thing to Google.
 

New Threads

Buy us a coffee!

Back
Top Bottom