怎么实现一个函数,将一个字符串转化成各种类型

liysky 2013-07-02 04:46:41
例如如下伪方法,但是

#include<stdio.h>
#include<stdlib.h>


[xxxx type] get_value(char * str, char * type)
{
if(strcmp(type, "int") == 0)
{
return atoi(str);
}else if(strcmp(type,"float") == 0)
{
return atof(str);
}

}


int main()
{
char *x = "33.01";
float t=0;
//t = atof(x);
get_value(x, "float");
printf("%f\n", t);

}


怎么修改上面代码能运行正确或其他实现方式?
...全文
174 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
图灵狗 2013-07-02
  • 打赏
  • 举报
回复

#include<stdio.h>
#include<stdlib.h>

void get_value(char * str, char * type, void* value)
{
    if(strcmp(type, "int") == 0)
    {
        *(int*)value = atoi(str);
    }else if(strcmp(type,"float") == 0)
   {
        *(float*)value = atof(str);
   }
 
}
 
 
int main()
{
   char *x = "33.01";
   float t=0;
   //t = atof(x);
    get_value(x, "float", &t);
   printf("%f\n", t);
 
}
赵4老师 2013-07-02
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <string.h>
void *get_value(char * str, char * type) {
    static int i;
	static float f;
	static double d;
	if (strcmp(type, "int") == 0) {
		sscanf(str,"%d",&i);
        return &i;
    } else if (strcmp(type,"float") == 0) {
		sscanf(str,"%f",&f);
        return &f;
    } else if (strcmp(type,"double") == 0) {
		sscanf(str,"%lf",&d);
        return &d;
    }
	return NULL;
}
int main() {
	char *x = "33.0123456789";
	void *pv;

	pv=get_value(x,"int"   );  if (pv) printf("%d\n"    ,((int    *)pv)[0]);
	pv=get_value(x,"float" );  if (pv) printf("%.6g\n"  ,((float  *)pv)[0]);
	pv=get_value(x,"double");  if (pv) printf("%.15lg\n",((double *)pv)[0]);
	pv=get_value(x,"short" );  if (pv) printf("%hd\n"   ,((short  *)pv)[0]);
    return 0;
}
//33
//33.0123
//33.0123456789
//
www_adintr_com 2013-07-02
  • 打赏
  • 举报
回复
boost 中有一个 lexical_cast 就是完成这个功能的. 只不过类型是模板参数, 不是字符串, 比如: int x = boost::lexical_cast<int>("123"); float v = boost::lexical_cast<float>("456.43"); std::string z = boost::lexical_cast<std::string>(234); 其实原理也非常简单, 就是源类型输出到流中, 再从流中读取目标类型.

69,381

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧