Monday, May 24, 2010

What is wrong with this C++ syntax?

#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using namespace std;








void convert(double numberSize, double current, string typeOF);


int main()


{


double number;


char measurement;





cout%26lt;%26lt; "Number\n%26gt;%26gt;";


cin %26gt;%26gt; number;


cout %26lt;%26lt; "Type\n%26gt;%26gt;";


cin %26gt;%26gt; measurement;





switch(measurement)


{


case "inches":


convert(0.083 333 333, number, "inches");


}


system ("pause");





return 0;


}


void convert(double numberSize, double current, string typeOF)


{


cout %26lt;%26lt; "Type: " %26lt;%26lt; typeOF %26lt;%26lt;


endl %26lt;%26lt; "Size: " %26lt;%26lt; numberSize * current;


}

What is wrong with this C++ syntax?
It looks like your variable "measurement" should be a character array instead of char. Then you use cin.getline to read it in. Finally you cannot use a switch statement with strings, so you would use an if statement.





Example:


char measurement[128];


std::cin.getline( measurement, 128);





std::string compareString;


compareString = measurement;





if(compareString.compare("inches") == 0)


{


// do stuff


}
Reply:Haven't done much C++ before but these lines:





cout%26lt;%26lt; "Number\n%26gt;%26gt;";


cout %26lt;%26lt; "Type\n%26gt;%26gt;";





should be,





cout%26lt;%26lt; "Number\n"%26gt;%26gt;;


cout %26lt;%26lt; "Type\n"%26gt;%26gt;;





The nesting of quotes is wrong at the moment.
Reply:Paraphrasing the compiler error in g++, "Case labels must be able to be reduced to an integer constant". "inches" is an array of chars. Your compiler probably should have given you an error.





If you use the 'char' type for your case labels, e.g. 'i', than it will work, however this limits you to single-letter input. If you really want to use strings, you can use a hash or a map to get an integer value from your known strings. It looks as if you're only altering a double (numberSize), so you can make a string to double map that will return the desired constant when you feed it a string, and scrap the switch. Something like:





struct CompStruct


{


bool operator()( const char* s1, const char* s2 ) const


{


return strcmp( s1, s2 ) %26lt; 0;


}


};





//inside main():





map%26lt;const char*, double, CompStruct%26gt; numberSizes;


numberSizes["inches"] = 0.083333333;


numberSizes["something"] = 0.123456789;


// etc.





string stringFromUser;


cin %26gt;%26gt; stringFromUser;


convert(numberSizes[stringFromUser], number, stringFromUser);








The syntax might be off, but I suppose it will work. Don't forget your error handling in case the key is not found.


No comments:

Post a Comment