最近遇到的C++数字和字符串的转换问题

最近遇到的C++数字和字符串的转换问题

1、

用itoa 和atoi  在头文件#include<cstidlib>

 

itoa用法:

char *  itoa ( int value, char * str, int base );
value
Value to be converted to a string.
str
Array in memory where to store the resulting null-terminated string.
base
Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.

其中返回值和str是一样的。

 

atoi用法:

int atoi (const char * str);
/* atoi example */
#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atoi */

int main ()
{
  int i;
  char buffer[256];
  printf ("Enter a number: ");
  fgets (buffer, 256, stdin);
  i = atoi (buffer);
  printf ("The value entered is %d. Its double is %d.\n",i,i*2);
  return 0;
}

2、sprintf 在头文件#include<cstdio>

int sprintf ( char * str, const char * format, ... );
Return value:
On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.
On failure, a negative number is returned.
/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}

3、字符串流的使用 

头文件:#include<sstream>

stringstream strm;             创建自由的stringstream对象
stringstream strm(s);              创建存储s的副本的stringstream对象,其中s是string类型的对象
strm.str();                 返回strm中存储打的string类型对象
strm.str(s);                将string类型的s复制给strm,返回void
string line,word;
while(ginline(cin,line))
{
     istringstrem strem(line);
     while(strem >> word)
     {
            //do something
      }    
}

class istream  可用来读取数据

class ostream 可用来写出数据

#include <sstream>
#include <iostream>
using namespace std;
int main ()
{
 
  int val1=255, val2=587;
  ostringstream format_message;
  format_message << "val1: " << val1 << endl
                   << "val2: " << val2 << endl;
  istringstream input_istring(format_message.str());
  cout << input_istring.str() << endl;
  cout << format_message.str() << endl;
  string dump;
   int val11,val22;
  input_istring >> dump >> val11 >> dump >> val22;
 
  cout << val11 << " " << val22 << endl;
  return 0;
}

 

 

posted on 2014-04-28 11:02 yi_meng 阅读(...) 评论(...) 编辑 收藏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值