I am pretty new to programming, so I guess be advised.
I am trying to take a user input, here for language, and compare it to an array.
So, if the user input is not within the array, go to while loop until a valid input is given. What I have here has been the closest I have gotten to that outcome but what it is doing is basically if the first letter of the input is a capital "E" the input is "valid". There are exceptions to that.
I was hoping someone here could tell me what's happening here.
Using greater than (>) as a comparison, as well as only comparing one element in your array, is why a single letter "E" is valid. You need to compare each ENTIRE string in your array. (==) for equals comparison.
That will expose another problem. If the user enters any strings other than "english" or "English," enters something like "ENGLISH," and the comparison fails.
BTW, PLEASE learn to use code tags, they make reading and commenting on source code MUCH easier.
HINT, you can edit your post and add the code tags.
#include <iostream>
#include <string>
#include <vector> // variable length container
#include <cctype> // ::tolower, ::toupper
int main()
{
// let's create a vector to hold some languages to compare to user input
std::vector<std::string> language { "English", "Russian", "Spanish" };
std::cout << "Please enter a language: ";
std::string input;
std::cin >> input;
// let's 'mangle' the user input so it is first character upper case, the rest lower
// http://www.cplusplus.com/reference/cctype/toupper/
// http://www.cplusplus.com/reference/cctype/tolower/
// initial char upper case
input[0] = ::toupper(input[0]);
// there are other ways to loop through a string and transform it
for (size_t itr { 1 }; itr < input.size(); itr++)
{
input[itr] = ::tolower(input[itr]);
}
for (size_t itr { }; itr < language.size(); itr++)
{
if (input == language[itr])
{
std::cout << "You entered \"" << language[itr] << "\", a valid choice. Thank you.\n";
}
}
}
1st test run:
Please enter a language: Swedish
2nd test run:
Please enter a language: russian
You entered "Russian", a valid choice. Thank you.