| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 3928 人关注过本帖
标题:[原创]把一串字符串转换为整型
只看楼主 加入收藏
kai
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:52
帖 子:3450
专家分:59
注 册:2004-4-25
结帖率:100%
收藏
 问题点数:0 回复次数:5 
[原创]把一串字符串转换为整型
把一串字符串转换为整型

// first method sscanf ANSI C #include <stdio.h> #include <stdlib.h>

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

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

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

system("pause"); return 0; }

#include <stdio.h> #include <stdlib.h> 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 <stdio.h> #include <stdlib.h> int main() { char* buffer = "1234"; int number;

number = atoi(buffer);

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

system("pause"); return 0; } //3. Method - strtoul (ANSI C) #include <stdio.h> #include <stdlib.h>

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 <sstream> #include <iostream>

using namespace std;

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

stringstream ss(buffer); ss>>number;

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

// compiled und run in VC 6.0 #include <sstream> #include <iostream>

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; }

[此贴子已经被作者于2004-05-10 15:22:17编辑过]

搜索更多相关主题的帖子: 整型 int quot 字符 ret 
2004-05-07 05:20
C++大粉丝
Rank: 4
等 级:贵宾
威 望:10
帖 子:477
专家分:0
注 册:2004-4-23
收藏
得分:0 
atol(const char*)

I am a big fan of c plus plus.
2004-05-10 10:27
timedcy
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2007-3-19
收藏
得分:0 
atoi()
2007-03-19 20:49
蓝一
Rank: 1
等 级:新手上路
帖 子:54
专家分:0
注 册:2007-5-25
收藏
得分:0 
才发现
KAI的代码真漂亮
2008-06-02 23:13
mqh21364
Rank: 1
等 级:新手上路
帖 子:642
专家分:0
注 册:2008-2-28
收藏
得分:0 



前不见古人,后不见来者。念天地之悠悠,独怆然而涕下。
2008-06-03 10:05
slongta
Rank: 1
等 级:新手上路
帖 子:32
专家分:0
注 册:2009-6-2
收藏
得分:0 
得学习了···

点上灯笼,跟着萤火虫,在夜里,找梦……
2009-12-29 22:53
快速回复:[原创]把一串字符串转换为整型
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015124 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved