2011-04-03 61 views
2

我收到以下錯誤:比較運算符==不工作,我如何使它工作? [CPP]

C:\Users\*******\Documents\CodeBlocksProjects\encryptText\main.cpp||In function 'int main()':| 
C:\Users\*******\Documents\CodeBlocksProjects\encryptText\main.cpp|14|error: no match for 'operator==' in 'givenText == 1'| 
C:\Users\*******\Documents\CodeBlocksProjects\encryptText\main.cpp|25|error: no match for 'operator==' in 'givenText == 2'| 
||=== Build finished: 2 errors, 0 warnings ===| 

使用下面的代碼:

#include <iostream> 
#include <string> 
#include "encrypt.h" 
#include "decrypt.h" 


using namespace std; 

int main() { 
startOver: 
    string givenText, pass; 
    cout << "Encrypt (1) or Decrypt (2)?" << endl << "Choice: "; 
    getline(cin, givenText); 
    if (givenText == 1) { 
     cout << endl << "Plain-Text: "; 
     getline(cin, givenText); 
     cout << endl << "Password: "; 
     getline(cin, pass); 
     cout << endl << encrypt(givenText, pass) << endl << "Restart? (Y/N)"; 
     getline(cin, givenText); 
     if (givenText == "Y") { 
      cout << endl; 
      goto startOver; 
     } 
    } else if (givenText == 2) { 
     cout << endl << "Ciphered-Text: "; 
     getline(cin, givenText); 
     cout << endl << "Password: "; 
     getline(cin, pass); 
     cout << endl << decrypt(givenText, pass) << endl << "Restart? (Y/N)"; 
     getline(cin, givenText); 
     if (givenText == "Y") { 
      cout << endl; 
      goto startOver; 
     } 
    } else { 
     cout << endl << "Please input 1 or 2 for choice." << endl; 
     goto startOver; 
    } 

    return 0; 
} 

我認爲這將是簡單的,如果(X == Y)之類的事情,但我想不是。我想要做什麼來解決這個問題?提前致謝!

回答

2

有對你的字符串中沒有隱式類型轉換,讓你無論是需要:

一)改變你的測試比較字符串:如果(givenText == 「1」)

b)在比較之前解析你的givenText爲一個整數:if(atoi(givenText.c_str())== 1)

玩得開心!

3

無法直接將字符串與int進行比較。在數字周圍使用引號。

1

1和2是整數,您不能將它們與字符串進行比較。改爲比較「1」和「2」。

2

givenText上的數據類型是字符串。你將它與一個整數進行比較。

有兩種方法來解決這個問題,簡單的一個:

if (givenText == "1") 

將於考慮1作爲一個字符串。

其他opion(這將與1,01,0randomCharacters01等等等等),是int givenTextInt = atoi(givenText.c_str());

現在你可以比較像這樣:

if (givenTextInt == 1)