There are several problems with your program, technically and logically.
Technical problems
If you are using C++, avoid using C functionality that has been replaced by C++ functionality, i.e., dont't use C strings when you can use C++ std::string
.
If you have the urge to use a C array do it but a std::vector
would be the better choice.
The next problem is you for
-loop. Learn the difference between =
(assignment) and ==
(equality). y==0
is a expression that return true
is y
is equal to 0
, false
otherwise. y=0
assignes y
to 0
. In your for
-loop you want to do the latter.
Logical problems
Ask yourself what you want to achieve? Here is what you are trying to do:
- Get a character as user input.
- Check if this character is a consonant.
- Output a corresponding message.
Your code is poorly designed from point 1 on: Why do you let the user input a string if you are only interessted in characters (since you are testing if the string is of length 1 and want to compare it to an array of characters)?
And here comes your biggest logical problem: In every loop step you test if the input is equal to a character. If it's not, you output "Not a consonant" and exit the loop. Let's investigate for the input of h
:
- First loop execution: Is
h
equal to b
? -> No -> "No consonant" and leave the loop
Consider this approach that avoides the use of C functions and solves your problem:
Edit: Since you had problems compiling my solution, I added a version not using C++11 features:
C++11
#include <iostream> /* std::cout, std::cin */
#include <vector> /* std::vector */
int main()
{
std::vector<char> consonants {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w',
'x', 'y', 'z'};
char c;
std::cin >> c;
for(const auto& letter: consonants){
if(c == letter){
std::cout << "Consonant" << std::endl;
return 0;
}
}
std::cout << "Not a consonant" << std::endl;
}
Compile with the -std=c++11
flag.
Classical solution
#include <iostream> /* std::cout, std::cin */
#include <vector> /* std::vector */
int main()
{
const char arr[] = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w',
'x', 'y', 'z'};
std::vector<char> consonants(arr, arr+sizeof(arr)/sizeof(arr[0]));
char c;
std::cin >> c;
for(int i=0;i<consonants.size();i++){
if(c == consonants[i]){
std::cout << "Consonant" << std::endl;
return 0;
}
}
std::cout << "Not a consonant" << std::endl;
}