Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,397 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,100 people online right now. Registration is fast and FREE... Join Now!




Convertion int 2 char

 
Reply to this topicStart new topic

Convertion int 2 char

basiloungas
19 Sep, 2006 - 02:08 AM
Post #1

New D.I.C Head
*

Joined: 19 Sep, 2006
Posts: 2


My Contributions
Hello There community
My first post in your site is this question

How can i convert an int to a char.
Simple question one might say but i can't find a way to utilize this!

CODE

#include <ctype.h>
#include <stdio.h>

int main()
{
    int x;
       char b;
    puts("give x ");
    scanf("%d",&x);
    getchar();
    if(isdigit(x)==0)
    {
        puts("HAHA");
        b=(char)x;
           printf("You pressed %c. FO\n",b);
    }
    printf("You pressed %d. FO\n",x);
    return 6;
}


first of all the isdigit() doesn't seem to work.
whether i type a number, or a char it always prints HAHA.

i have come up with the idea of using a char variable in the scanf and then using atoi() and then isdigit() but i want to know if i can do it from int to char!!!
Thank u very much and is someone know how plz tell me
User is offlineProfile CardPM
+Quote Post

Amadeus
RE: Convertion Int 2 Char
19 Sep, 2006 - 06:08 AM
Post #2

g++ -o drink whiskey.cpp
Group Icon

Joined: 12 Jul, 2002
Posts: 12,230



Thanked: 40 times
Dream Kudos: 25
My Contributions
Just to be clear, do you actually need to convert an int to a char, or are you looking to determine if a character actually is an integer? The isdigit function can be used as follows:
CODE

#include <ctype.h>
#include <stdio.h>

int main()
{
    char input;
    printf("Please enter a character or digit\n");
    scanf("%c",&input);
    if(isdigit(input)!=0)
    {
       printf("You have entered a digit\n");
       printf("The digit you have entered is %c\n",input);
    }
    else
    {
       printf("You have entered a character.\n");
       printf("The character you have entered is %c\n",input);
    }
    return 0;
}

but you may have to further define your requirements...namely if you actually need to convert an int to a char. If so, will the int ever be longer than 1 digit? If it will, then you'll need to convert to a char* instead...the sprintf function can be used...
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/5/08 02:58AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month