strcnvt.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* strcnvt.c -- try strtol() */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define LIM 30
  5. char * s_gets(char * st, int n);
  6. int main()
  7. {
  8. char number[LIM];
  9. char * end;
  10. long value;
  11. puts("Enter a number (empty line to quit):");
  12. while(s_gets(number, LIM) && number[0] != '\0')
  13. {
  14. value = strtol(number, &end, 10); /* base 10 */
  15. printf("base 10 input, base 10 output: %ld, stopped at %s (%d)\n",
  16. value, end, *end);
  17. value = strtol(number, &end, 16); /* base 16 */
  18. printf("base 16 input, base 10 output: %ld, stopped at %s (%d)\n",
  19. value, end, *end);
  20. puts("Next number:");
  21. }
  22. puts("Bye!\n");
  23. return 0;
  24. }
  25. char * s_gets(char * st, int n)
  26. {
  27. char * ret_val;
  28. int i = 0;
  29. ret_val = fgets(st, n, stdin);
  30. if (ret_val)
  31. {
  32. while (st[i] != '\n' && st[i] != '\0')
  33. i++;
  34. if (st[i] == '\n')
  35. st[i] = '\0';
  36. else // must have words[i] == '\0'
  37. while (getchar() != '\n')
  38. continue;
  39. }
  40. return ret_val;
  41. }