0

I'll like to convert my variable string into a integer:

Testing my code i notice I did something wrong.

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

int main(void)
{
    string s = get_string("Name: ");
    printf("%s\n %i\n", s, (int)s);
}

output:
Name: j
j
 41127952
Name: j
j
 40714256

I investigate the ASCII code and the value is 106. Why keeps outputting random numbers.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Joseamica
  • 77
  • 1
  • 1
  • 7
  • 5
    Firstly, do not use `cs50.h` because it distances you from the reality of C. Secondly, get a good beginner's book. Thirdly, look into `atoi`. – DeiDei Sep 07 '18 at 22:09
  • 1
    ... in particular, cs50's `string` type disguises a pointer, and thereby contributes to any number of incorrect expectations about how such objects should behave. Operating on a pointer itself is completely different from operating on the data to which it points. – John Bollinger Sep 07 '18 at 22:20

1 Answers1

1

You cast the pointer to char. So it is char * to int conversion . That pointer is the place where your chars are stored. If you want to print the ASCII code of the first character you need to

 printf("%s\n %i\n", s, *s);
0___________
  • 60,014
  • 4
  • 34
  • 74