从基本字符串到int类型的无效转换

时间:2018-09-19 12:41:18

标签: c++ string c++11 casting

我遇到了从基本字符串类型到整数类型的类型转换错误,并且我不知道如何解决矢量字符串和整数类型的矢量的情况。

  

在给定图像下方显示错误

s1[j]+=int(magazine[i]);

this is the error

1 个答案:

答案 0 :(得分:1)

您不能将字符串转换为整数。但是,可以使用stoi()获取字符串数字值,然后将其分配给整数:

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string str1 = "45"; 
    string str2 = "3.14159"; 
    string str3 = "31337 geek"; 

    int myint1 = stoi(str1); 
    int myint2 = stoi(str2); 
    int myint3 = stoi(str3); 

    cout << "stoi(\"" << str1 << "\") is "
         << myint1 << '\n'; 
    cout << "stoi(\"" << str2 << "\") is "
         << myint2 << '\n'; 
    cout << "stoi(\"" << str3 << "\") is "
         << myint3 << '\n'; 

    return 0; 
} 




Output:

stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337

还有其他一些方法,例如使用stringstream,您可能要看一下。希望它会有所帮助。

相关问题