Friday, July 31, 2009

Help with C++ Programming?

Below is my first C++ Program I have written for my C++ class. I compiled it and it said there was a problem concerning my forloop. Am I allowed to have a forloop inside an IF statement? Any help or tips would help alot. Explanation necessary. Redirecting me to an outside website won't do.





#include %26lt;iostream%26gt;


using namespace std;





int main()





{


char letter, confirm, x;


cout %26lt;%26lt; "What is your favorite letter?:\n";


cin %26gt;%26gt; letter;


cin.ignore();


cout %26lt;%26lt; "You chose ";


cout %26lt;%26lt; letter;


cout %26lt;%26lt; " as your favorite letter.\n";


cout %26lt;%26lt; "Are you sure? (Y=1/N=2)\n";


cin %26gt;%26gt; confirm;


if ( confirm == 2 ) {


for ( char x = 0; x %26lt; 1; x++ );


}


else {


cout %26lt;%26lt; "I like ";


cout %26lt;%26lt; letter;


cout %26lt;%26lt; " too. Thanks for playing.\n";


}


system ("pause");


}

Help with C++ Programming?
Next time it would be helpful to post the actual compiler error.





Your program compiled fine for me using gcc but you do have some logic errors.





(1) Your for loop doesn't actually do anything so you need to code an action for it. Using char x is fine by the way. A char is a valid numeric type to use in a loop.





(2) Your if statement will always be false. You are reading in type char for either 1 or 2 but your if statement is comparing against an int value. You need to change it to





if (confirm == '2')
Reply:Yes you are. But, your not allowed to declare x as a character.





for (int x = 0; x %26lt; 1; x++) {


/* your code */


}
Reply:Actually what happens when u store 0 in x is it stores ascii value of 0 in x that is 48 . when it checks x%26lt;1 which it checks 42%26lt;1... which does not satisfy ...


Solution


use x as integer


or


check the condition as x%26lt;'1'


No comments:

Post a Comment