Thursday, July 9, 2009

I am working on my first useful program in c! this is how far I got with it and I got stuck?

It is a calculator! And I am trying to make it give me a message when you input letters instead of numbers!








How would u write the whole program using functions????





this is the code! i use linux and the gcc compiler














#include %26lt;stdio.h%26gt;





int main( )


{


int z;


int x;





printf( "This is my first useful program ever created in C" );


printf( "\n" );


printf( "\n" );


printf( "Note that this calculator will subtract and divide the first integer by the second one" );


printf( "\n" );


printf( "\n" );





printf( "Input your first integer to be calculated:" );


scanf( "%d", %26amp;z);





printf( "Please input the second one:" );


scanf( "%d", %26amp;x);





printf ( "Added: %d \n", z + x );


printf ( "Subtracted: %d \n", z - x );


printf ( "Multiplied: %d \n", z * x );


printf ( "Divided: %d \n", z / x );


}

I am working on my first useful program in c! this is how far I got with it and I got stuck?
Two ways.





Check the return type. Look at http://www.cplusplus.com/reference/clibr... (scanf). It returns an int, which actually means something. Check if that integer matches EOF, and if it does, you know it failed to read in the input.





Only a beginner is excused from not checking for errors. Understand how the library functions work. If they set an error bit or return something on error, check for that.





The other way is to use fgets and strtol. Use fgets to take an input into a string. Then attempt to convert using strtol.
Reply:You will find lots of useful c programming sourcecode @ www.easytutor.2ya.com
Reply:Well, I'm not going to write the code for you--but one way you can figure out if inputs are characters or numbers, is to check its ascii code. If the ascii code of the input from the user is not that of a number, than return an error message.


No comments:

Post a Comment