类型错误

时间:2016-12-15 01:50:48

标签: c++

我正在尝试将字符串类型转换为项目的整数但是我一直收到无效的转换错误。我已经尝试了几种铸造方法,但是同样的错误仍在继续发生。我做错了什么,我怎么能解决这个问题?谢谢!我的代码如下。

Quarterback::Quarterback(string userInput){
    string tempWord;
    int count = 0;
    for (int i = 0; i < userInput.length(); i++){
        if (userInput[i] == ','){
            count++;
            if (count == 1){
                qbName = tempWord;
                tempWord = "";
            }
            if (count == 2){
                passCompletions = (int)tempWord;  //Issue occurs here
                tempWord = "";
        }
        else
            tempWord += userInput[i];
    }
}

2 个答案:

答案 0 :(得分:3)

您正在尝试将对象转换为基本变量。这是不可能的。你需要使用stoi()函数。

答案 1 :(得分:2)

您可以将字符串的每个字符强制转换为int。每个字符都是其ascii代码的整数值。字符串类具有[]运算符来访问每个字符。  您可以像这样更改代码的这一部分:

if (count == 2){
for(int i=0;i<tempWord.size();i++){
            passCompletions += (tempWord[i]-48)*pow(10,(tempWord.size()-i)); 
 //48 is the ascii of '0' and  this :(tempWord[i]-48) is the characters value and pow(10,(tempWord.size()-i)); is for setting the priority of the number for example 4567 the first character is 4 and your integer variable should be summed with 4000 and next time is 5 and it should be summed with 5*100.......
            tempWord = "";
}
    }