Advertisement

simple enumeration question

Started by July 02, 2002 03:12 AM
0 comments, last by 2DamnFunky 22 years, 5 months ago
hi there! ok i feel stupid asking this question but how do you read enumerated types. This is something thats been bugging me for ages even though im now learnign about classes. My books example doesnt work. heres the example #include <iostream.h> #include <iomanip.h> enum boolean {false, true}; main () { boolean a; cout << "Enter boolean value: "; int temp; cin >> temp; a = temp; cout << "A=" << a << endl; } however this creates the following errors - : error C2059: syntax error : ''constant'' : error C2143: syntax error : missing '';'' before ''}'' : error C2143: syntax error : missing '';'' before ''}'' : error C2440: ''='' : cannot convert from ''int'' to ''enum boolean'' Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast) so what the hell is going on. also whats the reason behind including the head iomanip.h?? It fails to mention that as well.
Which book are you using? Throw it away immediately and buy Accelerated C++! You have several problems in your code:

1. The headers do not have a ".h" suffix, and you do not need iomanip. Bear in mind that you will have to namespace-qualify names from the correct standard library headers. A decent book will explain namespaces.
2. false and true are C++ keywords, so you cannot use them like this. Call them something else or use upper-case.
3. main() must return int; if you don''t actually return a value, the compiler will return zero for you.
4. You can''t read directly into an enum value, you would do this by creating a class with an associated operator>>.
5. You don''t need to read directly into an enum for what you are doing, you can read directly into a bool.

Here''s a working example of what you are trying to do:

  #include <iostream>int main() {	std::cout << "Enter boolean value: ";	bool a;	std::cin >> a;	if(std::cin.fail())		std::cout << "That''s not a boolean value!" << std::endl;	else		std::cout << "A=" << a << std::endl;}  

This topic is closed to new replies.

Advertisement