Saturday, May 22, 2010

What is wrong with this c++ program?

I just started programming in C++ and need help. I created a basic adding program and it won't compile. What is wrong with it?


Here's the program:


//This program will add numbers


#include %26lt;iostream%26gt;


#include %26lt;cstdlib%26gt;


#include %26lt;cstdio%26gt;


using namespace std;





int main (int argc, char *argv[]);


{


char quit;





quit = '\0';


while (quit != 'q')


{


int x;


cout %26lt;%26lt; "enter the 1st value";


cin %26gt;%26gt; x;


int y;


cout %26lt;%26lt; "enter the 2nd value";


cin %26gt;%26gt; y;


int a;


a = x + y;


cout %26lt;%26lt; "The sum of the two values is:";


cout %26lt;%26lt; a %26lt;%26lt; endl;


}


system("PAUSE");


return 0;


}

What is wrong with this c++ program?
For starters, you DONT want a ; after your main function :





int main (int argc, char *argv[]);


^ WRONG!





Update: And the new errors are?


You probably need different header files -- specific to the compiler you are using. Which compiler are you using?





Try using stdio instead of cstdio and stdlib instead of cstdlib
Reply:along with above advices use


while(getchar(quit)!='q')





and add these lines after cout%26lt;%26lt;a%26lt;%26lt;endl;





cout%26lt;%26lt;"Enter q to quit";
Reply:mdigitale is correct about the stray semicolon after main. He expressed it a bit inaccurately though.





You don't want a semicolon after a function *definition*. You want it after a declaration. In your case, you are defining main. You are writing the code inside it. Careful on the semicolons.





mdigitale is however, incorrect about the headers. %26lt;iostream%26gt;, %26lt;cstdio%26gt;, and %26lt;cstdlib%26gt; are the correct forms. The change was made in the 98/99 revision of C++. Yes, that's nearly a decade ago. If you try to compile with the C style header format in any modern compiler, you will get a diagnostic message. Usually as a warning.





Just as a note, cstdlib isn't needed because you use no functions from it.





After removing the semicolon, you should have no further errors. If you do, do tell us **verbatim** what those errors are. As magical programmers seem to be, we aren't psychics. We do not read your mind remotely.





Your logic has an error in it. The while loop depends on quit, but quit will never change because you never asks for user input.





When posting code, please use a pastebin like http://www.rafb.net/paste/ . You can google for other nopaste or pastebin sites.The idea is to preserve indentation, and perhaps have formatting so we can actually read your code. Then we can help you.


No comments:

Post a Comment