自己实现atoi

bool myatoi(const char *s,int &num)
{
    cout<<(&s)<<endl;
    num=0;
    while (*s)
    {
        if ((*s)>='0'||(*s)<='9')
        {
            num=num*10+((*s)-'0');
        }
        else
            return false;
        s++;
        //cout<<"The address of pstr is: "<<static_cast<void*>(const_cast<char*>(str))<<endl;
        cout<<"prt:"<<(void*)s<<endl;
    }
    return true;
}
int main()
{
    char *s="12345";
    int num;
    myatoi(s,num);
    cout<<num<<endl;
    char s1='2';
    char s2='1';
    char s3=s1-s2;
    cout<<s3<<endl;
    int i=s1-s2;
    cout<<i<<endl;
    return 0;

}

首先要分清楚:字符数组和字符串的关系!
字符串存放在数组中,因此,一个字符数组可以存放几个串,单字符串函数只认字符串结束标志'';
1. strlen(wer wer):字符串为"wer_wer"这种字符串常量,系统会在其后自动补上'';而求字符串长度的函数strlen()只要遇见'';就返回函数值!而且''不算在其中!故返回值为7(空格也算一个字符!)
2. strlen(werwer) 其中的字符串为"werwer"而strlen函数遇到''即结束,故返回值为:3
3. ''不是空格,也不是回车!通过ASCII码表,你可知道,''是ASCII码值代表0(NULL);而空格的ASCII码为:  '32' 32 回车的ASCII码值为'13'  13

所以while (*s)当s++到最后*s=NULL,循环结束。

注意打印字符串指针不能使cout<<s;

因为<<操作符重载了吧,会默认输出字符串的值。必须显示转换为(void *)才可取得地址。

规范写法:cout<<"The address of pstr is: "<<static_cast<void*>(const_cast<char*>(str))<<endl; 类型转换安全
        cout<<"prt:"<<(void*)s<<endl;这样也可以。

注意cout<<&s;输出的是字符串指针的地址。

原文地址:https://www.cnblogs.com/Yogurshine/p/3668785.html