Advertisement
Taraxacum

str and int

Nov 16th, 2018
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int str2i(char* ch)
  6. {
  7.     int val = 0;
  8.     for (int i = 0; ch[i] != '\0'; i++) {
  9.         val = val * 10 + ch[i] - '0';
  10.     }
  11.     return val;
  12. }
  13.  
  14. void i2str(char* ch, int n)
  15. {
  16.     if (n == 0) {
  17.         ch[0] = '0';
  18.         ch[1] = '\0';
  19.     } else {
  20.         int digits[80] = { 0 };
  21.         int ord = 0;
  22.  
  23.         while (n > 0) {
  24.             digits[ord++] = n % 10;
  25.             n /= 10;
  26.         }
  27.  
  28.         ch[ord] = '\0';
  29.  
  30.         for (int i = 0; i < ord; i++) {
  31.             ch[i] = digits[ord - 1 - i] + '0';
  32.         }
  33.     }
  34. }
  35.  
  36. int main()
  37. {
  38.     char buffer[80] = { '\0' };
  39.  
  40.     int n = 0;
  41.     i2str(buffer, n);
  42.     cout << buffer << endl;
  43.     cout << str2i(buffer) << endl;
  44.  
  45.     n = 1;
  46.     i2str(buffer, n);
  47.     cout << buffer << endl;
  48.     cout << str2i(buffer) << endl;
  49.  
  50.     n = 29876543;
  51.     i2str(buffer, n);
  52.     cout << buffer << endl;
  53.     cout << str2i(buffer) << endl;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement