Life is Good.

Enhance Tech and English
随笔 - 65, 文章 - 20, 评论 - 21, 引用 - 0
数据加载中……

int 与 char* 互转


#include "stdafx.h"
#include "string.h"

int ConvertCharToInt(char* p)
{
  if (p == NULL)
    return -1;

  int n = 0;

  while(*p > '0' && *p < '9')
  {
    n *=10;
    n += *p - '0';
    p++;
  }

  return n;

}

bool ConvertIntToChar(int n, char* p)
{
  if (p == NULL)
    return false;

  int i = 0;
  char buf[256] = "";
  while(n)
  {
    buf[i++] = n % 10 + '0';

    n = (int) n / 10;
  }

  buf[i] = '\0';

  // reverse and copy
  int len = strlen(buf);
  int m = 0;
  for (int n = len-1; n > -1; n --, m++)
  {
    p[m] = buf[n];
  }

  p[m] = '\0';

  // copy
  //_strrev(buf);
  //strcpy(p,buf);


  return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
  char* p =  "1314";
  int n = ConvertCharToInt(p);

  char buf[256] = "";
  bool b = ConvertIntToChar(1314, buf);

  return 0;
}



posted on 2011-03-08 23:26 Mike Song 阅读(429) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理