how to avoid to printing the value of charecter in C?

gopi's Avatar, Join Date: Feb 2008
Newbie Member
Hi Friends,
I wrote a program in c to print a table for ant in teger as shown below

/**----------------------------------------**/
int a,b,c;
printf("Enter the value of a\n");
scanf("%d",&a);

for(b=1; b<= 20; b++)
{
c=a*b;
printf("%d X %d = %d\n",a, b,c );
}
/**-----------------------------------------**/

This program is working fine,when i give input as a number.

However,

[COLOR=DarkRed]in case,the given input is a charecter,[/COLOR]
Then it is showing some different output.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Thats because the character when converted into ASCII and multiplied will be numbers not as per expectation and so its giving unexpected output.
0
gopi's Avatar, Join Date: Feb 2008
Newbie Member
Hi Shabbir,
Thankyou very much for your reply.
Now what is the solution?
how can i use the function "isalpha()"
to avoid the above problem
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Code:
   char c;
   scanf( "%c", &c );
   if( isalpha(c) )
     printf( "You entered a letter of the alphabet\n" );
0
logical_brain's Avatar
Newbie Member
Check This code ( I only use cout and cin instead of scanf() and printf() )

Code:
#include <iostream>
#include <cstdlib>
#include <cctype>
using namespace std;

int valid_data(const char *data)
{
    int i=0;
    //TO Check -ve Number
    if(data[0] == '-')
        i++;
    //To check if only '-' sign is their
    if(data[i] == '\0' )
        return 1;
    while(data[i] != '\0')
    {
        if(!isdigit(data[i]))
            return 1;
        i++;
    }
    return 0;
}

int main()
{
	string n;
	cout<<"Enter Value of n : ";
	cin>>n;
	if(!valid_data(n.c_str()))
	{
	    int a = atoi(n.c_str());
        for(int i=1;i<=20;i++)
            cout<<a<<" X "<<i<<" = "<<a*i<<endl;
	}
    else
        cout<<"Invalid Value";
	return 0;
}
If you want a simpler code you read this about aoti() function
Quote:
About aoti(const char *)
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.
You can check whether returned value is zero or not. If it is zero then you can display message. "Invalid Value". But here we cannot check if user has entered zero (0) as value. If user has entered zero (0) as value then also your program will display "Invalid Value". Hence i do not suggest this.


Regards
0
gopi's Avatar, Join Date: Feb 2008
Newbie Member
Thanks allot!!!!