zl程序教程

您现在的位置是:首页 >  其他

当前栏目

关于String 转换到 unsigned short

转换 string 关于 short unsigned
2023-09-27 14:27:55 时间
这才知道,原来c_str 只能够返回const char*,没有办法,我查询还有没有别的转换的方法,很遗憾,都没有。
最近被一个小问题给弄晕呼了,没有办法人太笨了,基础又不好……

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

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

后来我查了一下CPPReference:
None.gifc_str 
None.gifSyntax: 
None.gif  #include  string
None.gif  const char* c_str();
None.gif
None.gifThe function c_str() returns a const pointer to a regular C string, identical to the current string. The returned string is null-terminated.
None.gif
None.gifNote that since the returned pointer is of type (C/C++ Keywords) const, the character data that c_str() returns cannot be modified.
None.gif 原文地址:http://www.cppreference.com/cppstring/c_str.html

这才知道,原来c_str 只能够返回const char*,
没有办法,我查询还有没有别的转换的方法,很遗憾,都没有。
最后我是采用这个办法解决的:
None.gif    nPort = atoi((char*)strPort.c_str()); 
我写了一个测试用的小东西:
None.gif#include  iostream
None.gif//#include  sstream.h
None.gif#include  string
None.gif//#include  winsock2.h
None.gif
None.gifusing namespace std;
None.gif
None.gif
None.gifvoid test()
ExpandedBlockStart.gif{
InBlock.gif//ostringstream oss;
InBlock.gif//oss.str("abc");
InBlock.gifstring strIP = "127.0.0.1"; 
InBlock.gifstring strPort = "2000";
InBlock.gif
InBlock.gif    char* szRemoteAddr = "";
InBlock.gif    unsigned short nPort ;
InBlock.gif
InBlock.gif
InBlock.gifszRemoteAddr = (char*)strIP.c_str();
InBlock.gif//nPort = atoi((char*)strPort.c_str());
InBlock.gifnPort = atoi((char*)strPort.c_str());
InBlock.gif
InBlock.gif
InBlock.gif//cout strIP endl;
InBlock.gif//cout szRemoteAddr endl;
InBlock.gifcout   "This is old one:"   strPort   endl;
InBlock.gifcout   "This is new one:"   nPort   endl;
InBlock.gif
InBlock.gif
ExpandedBlockEnd.gif}
None.gif
None.gifint main(int argc, char* argv[])
ExpandedBlockStart.gif
InBlock.giftest();
InBlock.gifreturn 0;
ExpandedBlockEnd.gif} 最后验证出来是正确的!
郁闷啊,这样一个小问题都把我搞得要死,唉……
知识分享之Golang——常用的类型转换int、string、float互相转换 知识分享之Golang篇是我在日常使用Golang时学习到的各种各样的知识的记录,将其整理出来以文章的形式分享给大家,来进行共同学习。欢迎大家进行持续关注。 知识分享系列目前包含Java、Golang、Linux、Docker等等。