2011-04-03 58 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)