类型转换错误

问题描述:

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

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]; 
    } 
} 
+0

你在做什么错是一个'的std :: string'不能转换成'int'。而已。结束。 –

+1

这是因为你不能将'string'转换为'int'。编译器(试图)告诉你,你不能将'string'转换为'int'。你做错了的事情是试图将'string'绑定到'int'。编译器的错误信息不清楚? – immibis

+0

最好不要在C++中使用C风格转换 - 这是一个C风格的转换,用括号括起来:'int x =(int)notAnInt;'。使用'int x = static_cast (notAnInt);'相反 - 它使你的意图更清晰。但是,这不会帮助您将字符串转换为int。你不能将一个字符串转换为int - 有没有人提到过这个呢? –

您试图将对象转换为原始变量。这是不可能的。你需要使用stoi()函数。

您可以将字符串的每个字符都转换为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 = ""; 
} 
    }