2016-12-15 66 views
-1

我想將一個字符串轉換爲一個項目的整數,但是我不斷收到無效的轉換錯誤。我已經嘗試了幾種鑄造方法,但仍然發生同樣的錯誤。我做錯了什麼,我該如何解決這個問題?謝謝!我的代碼如下。類型轉換錯誤

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 - 有沒有人提到過這個呢? –

回答

3

您試圖將對象轉換爲原始變量。這是不可能的。你需要使用stoi()函數。

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 = ""; 
} 
    }