0
votes

my code is

#include <stdio.h>
int main()
{
    int name;
    scanf("%d",&name);
    printf("%d",name);
}

Why when I enter "Hello","World","Good", etc it must show 2 ? Why 2 not the other number ? If I want to scanf string and printf ASCII code of it how should i do ? thankyou

3
You set up scanf to read a decimal value. You cannot enter strings like that with %dLostBoy

3 Answers

0
votes

You're not checking the return value of scanf which is most likely returning an error when you enter something that doesn't look like a number (e.g. Hello, World, Good are all invalid inputs).

That means the variable name is not being written so your printf call is actually exhibiting undefined behavior (by accessing an uninitialized variable) which probably explains your output of 2.

Keep in mind though, that because you're invoking undefined behavior, you technically could have gotten anything (it didn't have to be 2).

0
votes

To print ascii values of an entered string :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
  char array[100];   
    int i=0;
    printf("Enter string : ");
    scanf("%s",array);    // fixed as suggested in comments

    for(i=0;i<strlen(array);i++){

        printf("%d-",array[i]);

    }
    printf("\n");
    return 0;
}

Output of this code:

Enter string : hello
104-101-108-108-111-

EDIT:

As pointed out by good folks in the comments ... make sure array size is defined for some value that you think your input size will never exceed ...

0
votes

Why when I enter "Hello","World","Good", etc it must show 2 ? Why 2 not the other number ?

This is just because it is invoking Undefined Behavior. You will get anything. Sometimes it will give your desired output. Sometimes it will give my desired output. Sometimes it will give no one's desired output.

If I want to scanf string and printf ASCII code of it how should i do ?

Use getchar function to read your string 'character by character' and then print the ASCII value of each character using %d specifier.

#include <stdio.h>
int main()
{
    char name;
    while((name = getchar()) != '\n')
        printf("%c\t%d\n",name,name);
} 

NOTE: See, in my code I have not used array to store the string. Your string could be of any length.