为什么我用sizeof求字符串长度求出来不对呢?
#include <math.h>
#include <stdio.h>
#include <string.h>
int main()
{
int strToInt(char str[]);
char str[100];
int num;
while (gets(str)!=NULL)
{
num=strToInt(str);
printf("%d\n",num);
}
return 0;
}
int strToInt(char str[])
{
double num=0;
int i,j,len;
int a[11];
char str1[11];
if (str[0]>'9' || str[0]<'0')
{
return 0;
}
else if (str[0]=='\0' || str[0]=='\n')
{
return -1;
}
else
{
for (i=0,j=0;;)
{
if (str[i]>='0' && str[i]<='9')
{
str1[j]=str[i];
i++;
j++;
}
else
i++;
if (str[i]=='\0')
{
str1[j]=str[i];
break;
}
}
len=strlen(str1)-1;
for (i=0;len>=0;)
{
num+=(str1[i]-48)*pow(10,len);
i++;
len--;
}
return (int)num;
}
}
#include <stdio.h>
#include <string.h>
int main()
{
int strToInt(char str[]);
char str[100];
int num;
while (gets(str)!=NULL)
{
num=strToInt(str);
printf("%d\n",num);
}
return 0;
}
int strToInt(char str[])
{
double num=0;
int i,j,len;
int a[11];
char str1[11];
if (str[0]>'9' || str[0]<'0')
{
return 0;
}
else if (str[0]=='\0' || str[0]=='\n')
{
return -1;
}
else
{
for (i=0,j=0;;)
{
if (str[i]>='0' && str[i]<='9')
{
str1[j]=str[i];
i++;
j++;
}
else
i++;
if (str[i]=='\0')
{
str1[j]=str[i];
break;
}
}
len=strlen(str1)-1;
for (i=0;len>=0;)
{
num+=(str1[i]-48)*pow(10,len);
i++;
len--;
}
return (int)num;
}
}
上面是对的,但是要禁用string.h,于是我把strlen改成了sizeof/sizeof
#include <math.h>
#include <stdio.h>
#include <string.h>
int main()
{
int strToInt(char str[]);
char str[11];
gets(str);
printf("%d",strToInt(str));
while (gets(str)!=NULL)
{
printf("\n%d",strToInt(str));
}
return 0;
}
int strToInt(char str[])
{
double num=0;
int i,j,len;
int a[11];
char str1[11];
if (str[0]=='\0' || str[0]=='\n')
{
return -1;
}
else if (str[0]>'9' || str[0]<'0')
{
return 0;
}
else
{
for (i=0,j=0;;)
{
if (str[i]>='0' && str[i]<='9')
{
str1[j]=str[i];
i++;
j++;
}
else
i++;
if (str[i]=='\0')
{
str1[j]=str[i];
break;
}
}
len=sizeof(str1)/sizeof(char)-2;
for (i=0; len>=0;)
{
num+=(str1[i]-48)*pow(10,len);
i++;
len--;
}
return (int)num;
}
}
#include <stdio.h>
#include <string.h>
int main()
{
int strToInt(char str[]);
char str[11];
gets(str);
printf("%d",strToInt(str));
while (gets(str)!=NULL)
{
printf("\n%d",strToInt(str));
}
return 0;
}
int strToInt(char str[])
{
double num=0;
int i,j,len;
int a[11];
char str1[11];
if (str[0]=='\0' || str[0]=='\n')
{
return -1;
}
else if (str[0]>'9' || str[0]<'0')
{
return 0;
}
else
{
for (i=0,j=0;;)
{
if (str[i]>='0' && str[i]<='9')
{
str1[j]=str[i];
i++;
j++;
}
else
i++;
if (str[i]=='\0')
{
str1[j]=str[i];
break;
}
}
len=sizeof(str1)/sizeof(char)-2;
for (i=0; len>=0;)
{
num+=(str1[i]-48)*pow(10,len);
i++;
len--;
}
return (int)num;
}
}
但是就错了,求解啊