i was watching this video about type conversion and what the compiler does while converting from small byte formats to large byte formats(and vice versa) etc etc, and tried to write a code for it... but seems that function calls in my code are getting completely bypassed...

once again, here goes my sloppy code:

#include<stdio.h>

short char2shrt(void);
short int2shrt(void);
int shrt2int(void);


int main()
{
    char bool=0,option,op=0;
    do{
    puts("what do you want to do?: \n (1)character to short \n (2)int to short \n(3)short to int \n press 1,2 or 3:\n");
    scanf("%c",&option);
    switch(option)
        {
        case 1:
            char2shrt(void);
            break;
        case 2: 
            int2shrt(void);
            break;
        case 3: 
            shrt2int(void);
            break;
        }           
    puts("\ndo you wish to iterate once again?yes(1) or no(0):");
    scanf("%d",&bool);
    printf("\npresent state of bool:%d",bool);
    }while(bool==1);
}


short char2shrt(void)
{
    char ip;
    short op;
    puts("enter input:\n");
    scanf("%c",&ip);
    op=ip;
    printf("the output in type short is: %h",op);

}

short int2shrt(void)
{
    int ip;
    short op;
    puts("enter input:\n");
    scanf("%d",&ip);
    op=ip;
    printf("the output in type short is: %h",&op);
}

int shrt2int(void)
{
    short ip;
    int op;
    puts("enter input:\n");
    scanf("%h",&ip);
    op=ip;
    printf("the output in type int is: %d",&op);
}

the attepmts i made were as such:

  1. 1st created the functions akin to void foo(void) , that didnt work, then i tried making them like some_type foo(void) that didnt work either

  2. i thought making somthing like

    switch(option)
    {
    case 1:
    op=char2short(void);
    printf("the output in type short is: %h",op);
    break;
    .
    .

with "op" declared as char in the begining, and get them casted to the type i need at eace case: statements, and then make the functions here being of nature some_type foo(void) , and have them return in this manner

short char2shrt(void)
{
    char ip;
    short op;
    puts("enter input:\n");
    scanf("%c",&ip);
    op=ip;
    return(op);
}

that didnt work either...

i then thought maybe void foo(void) isnt allowed in C!! , and as i expected, turned out thats not the case either :(

man, its really hard work to be a beginer :(

can i get any pointers to where (theres probably more than a few) places im going wrong here ??

thanks a bunch in advance :)

What type did you enter with scanf("%c",&option);? What's the binary value of the input?
What type did you compare with case 1:? What's the binary value of the test value?

so case: takes only integer? or that im passing char to it in integer format makes it skip the loop altogeher? let me see that... hopefully it will solve this thing! :))

No, but that's what 1 is -- an integer. And what you input is a character.

yeah... i saw that mistake i was making when u told about the type... corrected it, well, the problems that were there then have gone now, but a few new ones cropped up :(

corrected code :

#include<stdio.h>
short char2shrt(void);
short int2shrt(void);
int shrt2int(void);
int main()
{
    char bool=0,op=0;
    int option=0;
    do{
    printf("\n\n\nwhat do you want to do?: \n ('1')character to short \n ('2')int to short \n('3')short to int \n press 1,2 or 3:\n");
    scanf("%d",&option);
    switch(option)
        {
        case 1:
            char2shrt();
            break;
        case 2: 
            int2shrt();
            break;
        case 3: 
            shrt2int();
            break;
        }           
    printf("\ndo you wish to iterate once again?yes(1) or no(0):");
    scanf("%d",&bool);
    printf("\npresent state of bool:%d",bool);
    }while(bool==1);

}
short char2shrt(void)
{
    char ip;
    short op;
    printf("enter input:\n");
    scanf("%c",&ip);
    op=ip;
    printf("the output in type short is: %h",op);
}
short int2shrt(void)
{
    int ip;
    short op;
    printf("enter input:\n");
    scanf("%d",&ip);
    op=ip;
    printf("the output in type short is: %h",&op);
}
int shrt2int(void)
{
    short ip;
    int op;
    printf("enter input:\n");
    scanf("%h",&ip);
    op=ip;
    printf("the output in type int is: %d",&op);
}

and this is the output i get :

for_dani_type

problems:
1. for case:1 no user input being taken
2. for case:2 user input being taken, but o/p isnt coming..
3. i am getting an output for case:3, although dont know if its right or wrong ...

any ideas to the weird behaviou for case:1 ??

i think in case:2 output short isnt coming out because the format specifier %h isnt correct?? that short == %h... is what i just found written on a few pages in the internet...

also, "bool" , is taking up values like 3,5 etc...

It's not weird at all. It's lack of understanding how scanf() works. Here's a series that explains the problems you are having. This will also help you next time you need to mix integer and character input using

@waltp : i never looked at the creator of that post before today :) i only looked at it very vaguely once, ill be looking at it in more detail now.

Why would the creator be important? Isn't the content the important thing? You could have saved yourself a lot of time and trouble by not vaguely reading it the first time, dontcha think? ;o)

Why would the creator be important?

its just im getting the link from the creator himself.. kinda neat:)

You could have saved yourself a lot of time and trouble by not vaguely reading it the first time, dontcha think?

yeah thats true :( but then i was looking for what scanf() does for my college homework.. and in college they used scanf() for everything!

one thing i would like to ask is that if there is any way i can see exactly whats in stdin?? whitespaces and everything? i read fgets() keeps whitespaces.. what about other ones? does it keep them too?

bdw, the examples in your link really helps :) thanks :)

yeah thats true :( but then i was looking for what scanf() does for my college homework.. and in college they used scanf() for everything!

Let me guess -- Turbo-C; India. Am I close?

one thing i would like to ask is that if there is any way i can see exactly whats in stdin?? whitespaces and everything? i read fgets() keeps whitespaces.. what about other ones? does it keep them too?

Depends on what you mean by see. It's not easy to see what's in the input stream. Since you mentioned stdin, it's every single key you pressed. Function and special keys have special codes and won't normally be in the stream.

Start a loop 
    Use one (and only one) type of input into a character buffer
    Another loop to output each and every character in the buffer

Break out of the program using Ctrl-C, or loop at least 3 times.
Then compare and see which keys you pressed are not in the output.

bdw, the examples in your link really helps :) thanks :)

Welcome.

Let me guess -- Turbo-C; India. Am I close?

india.. yes :) but i hope ur not lousy in scanf()==india :P
turbo-c >> it was used in our clg labs, but at home > codeblocks+cmd :)
i like the whole geeky feel of programming with green text on a black cmd background :)

back to the good stuff :
this is exerted from your link

int ch;         // define the character
    do              // loop until a good character is read
    {
        ch = getchar();             // read a character
    } while ( (ch == 0x20)  ||      // check for SPACE
             ((ch >= 0x09)  &&      // check for the 
              (ch <= 0x0D))         //    other whitespace
            );              
    return ch;

maybe i can use ch here as a container to hold all the unwanted stuff, and then "delete" them of some sort? is that a good idea? i was thinking like

  1. use malloc to assign space for 'collector' (im renaming 'ch' to collector)
  2. malloc gives more and more space to 'collector' based on length of my input
  3. once all collecting is done, use free to 'delete' it all, and thus keep input buffer clean for next read...

is this a good idea?
my main doubt here being with point number 2... i dont know if malloc can keep appending more space to a variable whose size it has already determined previously...
also, if free can be used in this manner..

as regards the code i posted,
each of the type conversion functions has these in them:

printf("enter input:\n");
    scanf("%c",&ip);

and thats what creating the trouble i guess... i was hoping to use the idea above to cure it...

hope im not being ludacris.. :(

major typo : i meant...

but i hope ur not saying "lousy in scanf()==india :P" ..

im sure your not doing that anyways:)

sorry for the weirdness..

You are overthinking the problem, trying to solve the problem from the wrong angle.

What did the link say about entering character strings? I know there was a recommended input function. Using that function will only complicate the reading of integers a little, but the input stream will be kept neat and clean. You won't have to worry about extra characters as long as your input buffer is adequate in size.

trying out a new thing.... lets see, ill post once the compilation is done...

still no cookie...

replaced

short char2shrt(void)
{
    char ip;
    short op;
    printf("enter input:\n");
    scanf("%c",&ip);
    op=ip;
    printf("the output in type short is: %h",op);
}

and then tried 2 things:

1.

short int2shrt(void)
{
    char input[40];
    int *ip;
    short *op;
    printf("enter input:\n");
    while (fgets(input, sizeof(stdin), stdin) && sscanf(input,"%d",ip) == 1)
    {
        printf("You entered %d",*ip);

    }
    *op=(*ip);
    printf("the output in type short is: %h",*op);
}

did not work, loop never ends, keeps giving me

you entered 'blah blah'

then i tried replacing while() like this:

2.

short int2shrt(void)
{
    char input[40];
    int *ip;
    short *op;
    printf("enter input:\n");
    fgets(input,sizeof(stdin),stdin);
    sscanf(input, "%c",ip);
    printf("You entered %c",*ip);
    *op=(*ip);
    printf("the output in type short is: %h",*op);
}

and voila .... program crashes!

i dont know what to do anymore :( can you please correct my code? i know im not supposed to directly ask for code help like this... but i just cant seem to do this... :(

thanks for keeping patience with me...

How many bytes does ip point to? None... You defined the pointers ip and op but no actual space.

You are making it too complicated. What did you read into input? At least 2 characters, and up to 40 (that is if your fgets() was right - which it isn't). So just look at the first character and you're done...

short int2shrt(void)
{
    char input[40];
    char  ip;
    short op;
    printf("enter input:\n");
    fgets(input,39,stdin);        // note the correction
    ip = input[0];                // this is the character you want
    printf("You entered %c",ip);  // remove the *
    op = ip;                      // just load it...
    printf("the output in type short is: %h",op);
}

I made minor changes to almost every line. But this is a lot closer (and easier) to what you want.

yaay! :)
1. code finally runs, no crashing, bypassing.. flows like its supposed to. only tweak i made after the one you posted was adding a

    while(getchar() != 'n')
    { 
        puts("cleaning stdin, if you can see this output, there were more than one whitespace leftout in stdin");

        }

block before the switch-case block, to clean stdin. now it works fine.

just one problem: (they are in love with me it seems..)

  1. i dont get any output for case1 (ie char2shrt()) and case2 (ie int2shrt()).. any ideas on that?
  2. i do get an output for case 3 (ie shrt2int()), but have to work out in binary if its correct or not.

also;
a questions squirming inside mybrain: *type* input[40] means what?

a. input is an array with 40 bytes, thus space for 10 ints(considering int==4bytes), 20 shorts, and 40 chars? or
b. input is an array of 40 blocks of memory, each block==sizeof(type) ,so total memory == *type**40

finally..
my resultant code:

#include<stdio.h>
void char2shrt(void);
void int2shrt(void);
void shrt2int(void);
int main()
{
    char bool=0,op=0;
    int option=0;
    do{
    printf("nnnwhat do you want to do?: n ('1')character to short n ('2')int to short n('3')short to int n press 1,2 or 3:n");
    fflush(stdout);
    scanf("%d",&option);
    //gotta keep stdin clean, scanf() messed it out , so here goes
    while(getchar() != 'n')
    { 
        puts("cleaning stdin, if you can see this output, there were more than one whitespace leftout in stdin");

        }

    switch(option)
        {
        case 1:
            char2shrt();
            break;
        case 2: 
            int2shrt();
            break;
        case 3: 
            shrt2int();
            break;
        }           
    printf("ndo you wish to iterate once again?yes(1) or no(0):");
    scanf("%d",&bool);
    printf("npresent state of bool:%d",bool);
    }while(bool==1);

}
void char2shrt(void)
{
    char input[40];
    char  ip;
    short op;
    printf("enter input:n");
    fgets(input,39,stdin);
    ip=input[0];
    printf("You entered %c",ip);
    op = ip;
    printf("nthe output in type short is: %h",op);
}
void int2shrt(void)
{
    char input[40];
    int   ip;
    short op;
    printf("enter input:n");
    fgets(input,39,stdin);        // note the correction
    ip = input[0];                // this is the character you want
    printf("You entered %c",ip);  // remove the *
    op = ip;                      // just load it...
    printf("nthe output in type short is: %h",op);
}// thankyou waltP
void shrt2int(void)
{
    char input[40];
    short  ip;
    int    op;
    printf("enter input:n");
    fgets(input,39,stdin);
    ip=input[0];
    printf("You entered %c",ip);
    op = ip;
    printf("nthe output in type int is: %d",op);
}

i dont get any output for case1 (ie char2shrt()) and case2 (ie int2shrt()).. any ideas on that?

'h' is a modifier to the %d specifier, you need them both: "%hd"

i do get an output for case 3 (ie shrt2int()), but have to work out in binary if its correct or not.

You don't need to fiddle with binary to determine correctness, just look at an ASCII table. Type a character and check the corresponding value in the table to verify. For example, if you type 'a' the result should be 97.

*type* input[40] means what?

It means input is an array of 40 objects of size "type". If "type" is char then you have an array of 40 bytes, if "type" is int then you have an array of 40 integers where each one is 4 bytes (going with your assumption). The size of an array of 40 will always be sizeof(type) * 40. Note that sizeof(char) is always 1, and char corresponds to the system's byte size, so an array of 40 char is equivalent to 40 bytes.

'h' is a modifier to the %d specifier, you need them both: "%hd"

yaaaayyy!!

just look at an ASCII table

YAAAAAAAAYYYYYYYYY!!!!!

It means input is an array of 40 objects of size "type". If "type" is char then you have an array of 40 bytes, if "type" is int then you have an array of 40 integers where each one is 4 bytes (going with your assumption). The size of an array of 40 will always be sizeof(type) * 40. Note that sizeof(char) is always 1, and char corresponds to the system's byte size, so an array of 40 char is equivalent to 40 bytes.

MEGA-YAAAAAAAAAAAAAAAAAAAAAYYY!!!!!!!
im marking this thread SOLVED!!

i am happy !! :))

a ton of thanks to you Mr Deceptikon, and Mr waltp!! :)
Thank you!!
:))

oh wait... :(
ip=input[0]

this just takes in one value, so i cant enter double digit numbers here! saw the output... whats the cure for that?? man i was so happy that it working... seems still a little left to go...

this just takes in one value, so i cant enter double digit numbers here!

I assumed that's what you intended. If you want to handle multiple digits then you're getting into the conversion stuff that scanf() does. It's not especially difficult for integer types (floating point types are a pain in the booty), but there are niggling edge cases that need to be considered for a truly robust conversion.

However, the core of the algorithm is this:

int stoi(const char *s)
{
    int result = 0;

    /* Positive numbers only! */
    while (*s && isdigit(*s)) {
        result = 10 * result + (*s - '0');
        ++s;
    }

    return result;
}

You progressively get a digit, find it's numeric value (by subtracting the character '0', see if you can figure out why this works), add that value to the result, then multiply or shift the result left by a tens place to make room for the next digit. For the string "123", the trace would look like this:

10 * 0 + ('1' - '0')  // result == 1
10 * 1 + ('2' - '0')  // result == 12
10 * 12 + ('3' - '0') // result == 123

Or you can call atoi() and not have to actually write the code. ;-)
Look it up...

i assume since i have varied kinds of input data types in different functions(int2shrt, char2shrt etc..), so i'll need to make an stoi() that return different types as well...
or will int stoi() suffice for all the cases ? in that case, i can also use atoi() directly too right?

You progressively get a digit, find it's numeric value (by subtracting the character '0'...

i can think of two cases:
1. its related to the ASCII value of the characters? '0' being some value x, and '1' has value (x+1)??
2. the other one being related to pointers, and array indexing starting with 0, but as ur doing (*s-'0') instead of (s-'0') so probably its not the case..

Some things you need to figure out:

1) What happens when you pass a character variable to a function that wanted an integer?
2) What happens when you return an integer into a character variable?

Are these safe?
Do you need to convert first?

Research them...

Some things you need to figure out:

1) What happens when you pass a character variable to a function that wanted an integer?
2) What happens when you return an integer into a character variable?

Some things you need to figure out:

1) What happens when you pass a character variable to a function that wanted an integer?
2) What happens when you return an integer into a character variable?

from what i understand:

  1. char==1byte==8bits
    therefore, if i call 'ch' a char variable, and assign it value 5, then binary ways:

ch= 10000101 (signed negative char)

when i pass ch=5 into a variable of type int; the lower 3 bits , ie 101 gets bit-mapped into the lowest LSB's of 32bit int,
so its like: 1xxxxxxx-xxxxxxxx-xxxxxxxx-xxxxx101 (assuming a negative number)
what happens to the middle 'x' es area is mystery to me too :(
that's why i wanted to write this code to give me data to understand the theory behind it..

and yes...
whatever i wrote above can be absolutely wrong too :D

im looking it up now... lets see....

and now that you said it, i had a question too, what happens when the sign bit of char value -5 (ie binary: 10000101) goes into a higher byte format (a 2byte short lets suppose) ,then what happens to the msb 1 of 10000101 in 1xxxxxxx-10000101, does it stay 1? coz i assume then the value gets changed.... ?? also, howwill it effect the feild of x-es??? <confusion-confusion!!>

this video explained a lot...

from what i understand:

  1. char==1byte==8bits
    therefore, if i call 'ch' a char variable, and assign it value 5, then binary ways:

ch= 10000101 (signed negative char)

How do you get 10000101? Where did the first 1 come from? What you have is -123. Just because it's signed does not mean the first bit is 1. It just means the 1st bit is used as the sign bit.

My question was referring to what happens when you have something like

int a;
char b;
a = b;

Is this safe? What happens to the values when you assign values to a different type? This also affects:

int a = 23;
int s;
sqrt(a);

since sqrt() takes doubles, not ints. What happens to the int ?

What you have is -123

+5= (0)0000101
+123= (0)1111011,
thus -123= ( (NOT)(+123) )+1= (1)0000100+1=(1)0000101 // two's compliment form

also, two's compliment@(+5)= (1)1111011 = -5, coz only then (+5)+(-5)=0
thus, (-5) != (1)0000101

i think im getting it now :) thanks for pointing it out :)

as regards

int a;
char b;
a = b;

lets see....

int = 4bytes, char=1byte...

so when we do

a = b;

the char byte gets copied into the lowest byte of int.

results: (what i can think of)
1. consedering both int and char were positive numerical values, i think no harm would be done... the first 3 bytes would be 0's anyways, however
2. if it was like char b='A', then value stored in b=65, (binary: 10000001), and when it gets copied into int a, although a will contain

(0--0)(0--0)(0--0)(10000001)

byte4|byte3|byte2|byte1= value of char

i dont think an integer can give 'A' output to the console... although data stored is the same...

did i make sense?

i think im getting it now :) thanks for pointing it out :)

Looks like you are...

the char byte gets copied into the lowest byte of int.
....
(0--0)(0--0)(0--0)(10000001)

Good...

i dont think an integer can give 'A' output to the console... although data stored is the same...

Try it... Define a char and and int. Load 65 into both. Now output both. What happens? Why?

did i make sense?

You're doing good :)

its like i thought it would be, the data remains same, only the output format is different

when 65 is loaded to both int and char, output on console shows 65 for int, and A for character...

as regards why...
i think its because integer displays the data stored in it, while char compares its data to ASCII, and displays the character that matches it (ie the data stored in it).

is it like that?? i havent looked it in the internet.. really, im just too excited about it to look anywhere, im just blurting out my thoughts via the keyboard into this page .... am i going the right way?

so to think of it... each type translates the binary in its own way, and as long as the binary remains same, the output remains "understandably" different... just like 65 and 'A' are...

so if we apply this logic to the

ip=input[0]

problem....

back there, the issues were:

  1. only one digit was loading into the cases like char2shrt() int2shrt() and i wanted multiple inputs
  2. as a solution to this problem, came int stoi() and atoi() , but i had a doubt with the return types being always int

so if im getting it right, then although the return type is int in a function like char2shrt(), as long as the return value stays small, and within the limits of char (and thus short too) , the binary wont be messed up, and we can retrieve good data from int , pass it to char or short, and get an "understandably" different output.. just like 65 and 'A'....

right??

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.