简体   繁体   English

在 C++ 中将 str[str.size()-1] 转换为整数?

[英]Cast str[str.size()-1] as interger in c++?

I have no idea how to cast str[str.size()-2] and str[str.size()-1] as integers.我不知道如何将str[str.size()-2]str[str.size()-1]为整数。 I need to return answers as integers.我需要以整数形式返回答案。

int main()
{
    cin>>D;
    int k;
    int z;
    int*tab=new int [D];
    for (int i=0;i<D;i++)
    {
        cin>>tab[i];    
    }
    
    for (int i=0;i<D;i++)
    {
        z=silnia(tab[i]);
        string str = to_string(z);
        if (str.size()>1)
            cout<<str[str.size()-2]<<" "<<str[str.size()-1];
        else
            cout<<"0 "<<str[0];
        cout<<endl;
        suma=1;
    }    
    
    return 0;
}

I think you can use substr and atoi .我认为你可以使用substratoi

string std::string::substr (size_t pos = 0, size_t len = npos) const; Generate substring Returns a newly constructed string object with its value initialized to a copy of a substring of this object.生成子字符串返回一个新构造的字符串对象,其值初始化为该对象的子字符串的副本。 The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).子字符串是对象的从字符位置 pos 开始并跨越 len 个字符的部分(或直到字符串的结尾,以先到者为准)。 http://www.cplusplus.com/reference/string/string/substr/ http://www.cplusplus.com/reference/string/string/substr/

int atoi (const char * str); Convert string to integer Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.将字符串转换为整数 解析 C 字符串 str,将其内容解释为整数,该整数作为 int 类型的值返回。 http://www.cplusplus.com/reference/cstdlib/atoi/ http://www.cplusplus.com/reference/cstdlib/atoi/

you can include sstream library then simply do the following:您可以包含 sstream 库,然后只需执行以下操作:

stringstream a(str[str.size()-2]);
int x;
a >> x;

now x has the value of whatever ur string was and you can freely return x现在 x 具有任何你的字符串的值,你可以自由地返回 x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM