牵着老婆满街逛

严以律己,宽以待人. 三思而后行.
GMail/GTalk: yanglinbo#google.com;
MSN/Email: tx7do#yahoo.com.cn;
QQ: 3 0 3 3 9 6 9 2 0 .

关于String 转换到 unsigned short

最近被一个小问题给弄晕呼了,没有办法人太笨了,基础又不好……

我最近要把一个String的数值转换为 unsigned short int类型,Socket里面的sockaddr_in的sin_port使的就这。

开始尝试了使用标准库istringstream和ostringstream来解决,也就是:
 std::istringstream  str(strPort); 
 unsigned 
short nPort;
 str
<<strPort; 
 str
>>nPort; 
但是很遗憾,转换的数值是错误的。
后来看到了可以用:
nPort = (char*)strPort.c_str();
转换到 char*,我就类似的使用了:
nPort = (unsigned short)strPort.c_str();
结果数值还是错误的!

后来我查了一下CPPReference:
c_str 
Syntax: 
  #include 
<string>
  
const char* c_str();

The function c_str() returns a 
const pointer to a regular C string, identical to the current string. The returned string is null-terminated.

Note that since the returned pointer 
is of type (C/C++ Keywords) const, the character data that c_str() returns cannot be modified.
原文地址:http://www.cppreference.com/cppstring/c_str.html

这才知道,原来c_str 只能够返回const char*,
没有办法,我查询还有没有别的转换的方法,很遗憾,都没有。
最后我是采用这个办法解决的:
    nPort = atoi((char*)strPort.c_str()); 

我写了一个测试用的小东西:
#include <iostream>
//#include <sstream.h>
#include <string>
//#include <winsock2.h>

using namespace std;


void test()
{
//ostringstream oss;
//oss.str("abc");
string strIP = "127.0.0.1"
string strPort = "2000";

    
char* szRemoteAddr = "";
    unsigned 
short nPort ;


szRemoteAddr 
= (char*)strIP.c_str();
//nPort = atoi((char*)strPort.c_str());
nPort = atoi((char*)strPort.c_str());


//cout<<strIP<<endl;
//cout<<szRemoteAddr<<endl;
cout << "This is old one:" << strPort << endl;
cout 
<< "This is new one:" << nPort << endl;


}


int main(int argc, char* argv[])

test();
return 0;
}
最后验证出来是正确的!
郁闷啊,这样一个小问题都把我搞得要死,唉……

posted on 2006-04-29 17:33 杨粼波 阅读(7868) 评论(5)  编辑 收藏 引用 所属分类: 学习笔记

评论

# re: 关于String 转换到 unsigned short 2006-05-02 17:19 路过甲

用stringstream  回复  更多评论   

# re: 关于String 转换到 unsigned short 2006-05-04 15:56 tx7do

测试了下,确实可以,
但是,我用VC7没有问题,但是使用G++就说找不到sstream,郁闷了。  回复  更多评论   

# re: 关于String 转换到 unsigned short 2006-05-05 11:18 路过甲

gcc里面应该是
#include "std_sstream.h"  回复  更多评论   

# re: 关于String 转换到 unsigned short 2006-10-16 17:30 路过乙

数字字符串肯定不能直接转为数字,一般使用atoi比较方便。
不过可以用nPort = atoi(strPort.c_str());
基础很重要的。
  回复  更多评论   

# re: 关于String 转换到 unsigned short 2008-04-25 20:35 xxxx

unsigned int nIPaddress = strtoull(ip.c_str(),NULL,10)  回复  更多评论   


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