基于这个严格的示例,如何在C编程语言中将字符串转换为整数?

基于这个严格的示例,如何在C编程语言中将字符串转换为整数?,c,integer,C,Integer,例如: // variable fixed Char specialstring[PATH_MAX]; int integernumber; int xx = 1 ; int yy = 1 ; strncopy( specialstring, "1369", ... bla); // here we go !! help there below please integernumber=atoi(specialstring); mvprintw( yy , xx , "%d" , in

例如:

// variable fixed
Char specialstring[PATH_MAX];
int integernumber;
int xx = 1 ; 
int yy = 1 ; 
strncopy( specialstring, "1369", ... bla); 


// here we go !! help there below please
integernumber=atoi(specialstring);
mvprintw( yy , xx , "%d" , integernumber );
请帮我把specialstring转换成整数好吗


谢谢

您可以使用此选项将字符串转换为int,而无需使用atoi

int Convert(char * str)
{
    int result =0;
int len=strlen(str);
for(int i=0,j=len-1;i<len;i++,j--)
    {
    result += ((int)str[i] - 48)*pow(10,j);
    }

   return result;
}
int转换(char*str)
{
int结果=0;
int len=strlen(str);

对于代码中的(inti=0,j=len-1;i,您有两个错误:

1)
strncopy
不是您想要的功能。它的手册页: 这里,
s1
是目标字符串,
s2
是源字符串,
n
是要从源中复制的字符数

如此正确:

strncopy( specialstring, "1369", ... bla); 
     ^                            ^ should be `n` num of chars you wants to 
    strncpy                         copy in `specialstring`
进入

2)
specialstring
的声明中,
Char
是错误的,您应该写小的
c

Char specialstring[PATH_MAX];
^ small letter

char  specialstring[PATH_MAX];
3)
atoi()
是将字符串转换为int的正确函数,如果要在不使用
atoi
的情况下进行转换,可以使用
sscanf()
函数,如:

sscanf(specialstring,"%d", &integernumber);

查看此内容:

atoi
已将字符串(
specialstring
)转换为数字(
integernumber
),您的问题是什么?您希望在不使用
atoi
的情况下进行此转换吗?
atoi
有什么问题吗?
specialstring
中有什么内容?这应该没问题,输出是什么?[blog]:"检查这个答案。-1.这假设ASCII。在给定平台上实现
atoi
可能会考虑到它使用另一种形式的存储字符这一事实,这就是为什么应该使用它。此外,
pow
对浮点值进行操作,这在这种情况下是完全不必要的。对不起……但是您可以解释更多…这不是一个将字符串转换为整数的有效代码吗?如果使用该代码的平台使用ASCII,并且作为程序员,您不介意在代码中包含不必要的操作,则该代码是有效的。更不用说它不支持由
atoi
正确转换的有符号数字。
sscanf(specialstring,"%d", &integernumber);