c语言问题请教

selg1984 2012-05-23 02:59:52
设计个函数 int atoi(char *s,int len) 输入:"1234567" 3 输出:123
...全文
125 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
自信男孩 2012-05-23
  • 打赏
  • 举报
回复

int my_atoi(const char *str, int len)
{
if (str == NULL || len > strlen(str))
{
return -1;
}

int num;
char *buf = malloc(len+1);
if (buf == NULL)
{
fprintf(stderr, "line: %d, error: %s\n", __LINE__, strerror(errno));
exit(EXIT_FAILURE);
}
memset(buf, 0, len+1);
memcpy(buf, str, len);
num = atoi(buf);
free(buf);
return num;

}

调用系统提供的函数atoi将字符转换成整型。
cobra_chen 2012-05-23
  • 打赏
  • 举报
回复
不好意思,一直用C++的编译器。
所以用了C++的风格。
要转成C,把变量声明放到函数头部。
另外atoi本身就有在<stdlib.h>

[Quote=引用 5 楼 的回复:]

C/C++ code

// 完整的
int atoi_ex(const char *s,const int len ,int *num)
{
if (NULL == s) return -1;
char check[128] = {0};
sprintf(check ,"%u" ,(unsigned int)-1);
if (strlen(s) > strle……
[/Quote]
赵4老师 2012-05-23
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]
C/C++ code
//int atoi(char *s,int len) 输入:"1234567" 3 输出:123
#include <stdio.h>
char str[]="1234567";
int atoi(char *s,int len) {
int i;
char f[4];
if (NULL==s) return 0;
if (l……
[/Quote]
这4星不是白给的吧。(^_^)
cobra_chen 2012-05-23
  • 打赏
  • 举报
回复

// 完整的
int atoi_ex(const char *s,const int len ,int *num)
{
if (NULL == s) return -1;
char check[128] = {0};
sprintf(check ,"%u" ,(unsigned int)-1);
if (strlen(s) > strlen(check)) return -2;

char convert[128] = {0};
if (len >= strlen(s)) strcpy(convert ,s);
else strncpy(convert ,s ,len);
//*(s+len) = '\0';
*num = atoi(convert);
return 0;
}

// 简单的
int atoi_ex(char *s,int len)
{
*(s+len) = '\0';
return atoi(s);
}
赵4老师 2012-05-23
  • 打赏
  • 举报
回复
//int atoi(char *s,int len) 输入:"1234567" 3 输出:123
#include <stdio.h>
char str[]="1234567";
int atoi(char *s,int len) {
int i;
char f[4];
if (NULL==s) return 0;
if (len<1 || 9<len) len=9;
sprintf(f,"%%%dd",len);
sscanf(s,f,&i);
return i;
}
void main() {
printf("atoi(%s,3)==%d\n",str,atoi(str,3));
}
//atoi(1234567,3)==123
無_1024 2012-05-23
  • 打赏
  • 举报
回复

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

int My_atoi_1(char *sourcePtr,int len)
{
int result = 0;
for (int i = 0;i < len;++i)
{
if (sourcePtr[i] >= '0' && sourcePtr[i] <= '9')
{
result = result * 10 + sourcePtr[i] - '0';
}
else
{
return -1;
}
}
return result;
}
int main()
{
char *str = "123465";
int sum = My_atoi_1(str,3);
printf("%d\n",sum);
return 0;
}
vivian_sxg 2012-05-23
  • 打赏
  • 举报
回复
把atoi里面的字符串的长度,取你自己想要的长度就可以了吧
無_1024 2012-05-23
  • 打赏
  • 举报
回复
一个循环 搞定啊

70,020

社区成员

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

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