把一串字符串转换为整型

作者在 2006-07-31 10:47:00 发布以下内容

// first method sscanf ANSI C
#include <iostream> 
#include <cstdlib>

using namespace std;
int main()
{

char * buffer = "4711";
int number;
int ret;

ret = sscanf(buffer, "%d", &number);

if (ret) // success
{
printf("%d\n", number);
}

system("pause");
return 0;
}

#include <iostream> 
#include <cstdlib>
using namespace std;
int main()
{

char * buffer = "4744";
int i;
char s[20];
double d;
int ret_ok;
ret_ok = sscanf(buffer, "%d - %s - %g", &i, s, &d);

if(ret_ok)
printf("%d\n", i);

system("pause");
return 0;

}

// second method atoi (ANSI C)
#include <iostream> 
#include <cstdlib>
using namespace std;
int main()
{

char* buffer = "1234";
int number;

number = atoi(buffer);

printf("%d\n", number);

system("pause");
return 0;
}

//3. Method - strtoul (ANSI C)
#include <iostream> 
#include <cstdlib>
using namespace std;

int main()
{

char * buffer = "123456";
const int radix = 10;
unsigned long number;
char * error;

number = strtoul(buffer, &error, radix);

if (!*error)
{
/* no error */
printf("%d\n", number);
}
system("pause");
return 0;
}

4. Method - stringstream (ANSI C++)
// compiled und run in VC 6.0,
// BC don't support sstream.h

#include <iostream>
#include <cstdlib>
#include <sstream>
using namespace std;

int main()
{
  char * buffer = "1234";
  int number;

  stringstream ss(buffer);
  ss>>number;

  if(!ss)
  {
    /* error */
    exit(1);
  }
  else
    cout<< number<<endl;

  system("pause");
  return 0;
}


// compiled und run in VC 6.0
#include <iostream>
#include <sstream>
#include <cstdlib>
using namespace std; 

int main()
{
  char * buffer = "123456";
  stringstream ss;
  ss << buffer;

  // now ist ss.str() die number in Stringrepresentation.
  cout<<ss.str()<<endl;
  // or through the number you get the value
  int number;
  ss>>number;
  cout<<number<<endl;
 
  system("pause");
  return 0;
}

那么如何将字符串转换为 double 类型呢? 方法是一样的,只需要将上面例子中的整形改为 double 类型就可以了。 那么改为 float 类型又如何呢? 改为float 类型你会遇到一点麻烦, 那就是精度上的丢失, 建议使用 double 类型。

如何将整形,float 或 double 类型转换为 字符串呢? 我在那个计算器程序中写了一个 doubleToString(...); 函数。如果是 double 转换到 string, 大家把这个函数直接拿来用就是了。如果是 int 转换到 string 或 float 转换到 string, 那么大家将这个double 类型改为你想要的类型就可以了,或者用模板来实现通式。

 
programming | 阅读 3516 次
文章评论,共1条
kai(作者)
2006-08-04 05:45
1
heliujin,
很遗憾,熟悉我的朋友都知道, 我是不用QQ 的。 很乐意和大家一起探讨编程, 包括C++ 编程。
游客请输入验证码

kai
浏览94820次