So while input is not x I want the program to run a loop. However, if I enter two letters at one time it prints them both out. I only want it to print out 1 how do I check if the user enters more than one character?
This is what I have. If the user enters some like hey it will output the 'h' and the 'y' on two different lines. I want to be able to check if the user had entered more than 1 letter and if they did run the else statement.
int main()
{
char letter = 'a';
while (letter != 'x')
{
cout << "Please enter a letter." << endl;
cin.get(letter);
if (isalpha(letter) && letter != 'x')
{
cout << "The letter you entered is " << letter << endl;
cout << endl;
cin.clear();
}
elseif (letter != 'x' && !isalpha(letter))
{
cout << "This is not a letter. Please try again." << endl;
cout << endl;
cin.clear();
}
cin.ignore();
}
return 0;
}
If all you want is to get confirmation from user to terminate application (at least that's what your code shows) then you don't want to run a loop until the user enters specific combinations of letters.
such design is unnecessary overhead, and will most likely force the user to terminate the console in some other way such as hitting the "X" button and just close the console or the user may just press CTRL + C, why would user follow your exit logic?
more over, you didn't even tell the user what should he input on command line?
what you want is to give user specific options, and default to exit.
Otherwise if you insist for what ever reason here is sample code:
#include <string>
#include <iostream>
int main()
{
char letter = 'a';
// tell user what we want
std::cout << "enter 'x' letter to exit: ";
while (letter != 'x')
{
std::string input = "";
// get what ever user inputs, whole line until new line
std::getline(std::cin, input);
// get first character, ignore the rest, skip if no input
if (!input.empty())
letter = input.at(0);
if (input.size() > 1)
{
// TODO: do something with the rest of char's in input
}
if (!std::cin.good())
{
// TODO: handle error here or just break
std::cout << std::endl << "input error!" << std::endl;
break;
}
// TODO: input the rest of the code here
}
return 0;
}
If the user enters some like hey it will output the 'h' and the 'y' on two different lines.
Line 8 extracts the 'h'. Line 13 prints it.
Line 24 ignores a single character. So it ignores the 'e'.
The loop runs again. Line 8 extracts 'y' and line 13 prints it.
You probably want to ignore everything up to an end of line. Add #include <limits>
at the top and change line 24 to cin.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore through end of line