I thought I would try and write some encryption program that converts input to numbers in a file.
I made a table, giving each letter its own number. The code itself went a little like this for each letter:
if (Letter = "P")
{
FILEO.open("Encrypted.txt", ios::app);
FILEO << " 259";
FILEO.close();
}
It came up with "cannot convert from 'const char [2]' to 'char'"
Can anyone suggest how I would go about actually getting a number from a letter?
If Letter is a char, use a char literal:
if (Letter == 'P')
...
Your conditional checking is wrong. It should be ==, not =. A single = means assignment whereas a == means conditional checking.
I am assuming Letter is a character array. In that case, you can use strcmp to compare it with P.
if(strcmp(Letter, "P") == 0)
{
// rest of the code
}
Take a look at the strcmp function reference here, if necessary.
If Letter is simply a char, then you need to compare it with P like this -
if(Letter == 'P')
{
// rest of the code
}
A single quote around a character makes it a character literal, which then can be compared against another character using ==.
You can not compare C++ char to C++ string! You should use single quote for chars, not double quotes. Also, the C++ equals operator is not =, it is ==. the single = is the assignment operator.
You should write the condition like this :
if (Letter == 'P')
{
FILEO.open("Encrypted.txt", ios::app);
FILEO << " 259";
FILEO.close();
}
(Letter = "P")
This is an assignment, not comparison.
You probably meant (Letter == "P") which would also be wrong, you need strcmp.
you need to use strcmp to compare....as = is an assignment operator....
I would recommend that when you give us an error message as you did, you give us the full message - including line numbers so that we know where the error occurred (or tell us what line it occurred at). Paying attention to those line numbers can greatly help finding the true problem.
Given the error message I'm assuming Letter is of type char - you need to understand the difference between literal strings (enclosed in double quotes) and literal characters (enclosed in single quotes).
As Luchian also mentioned, you have an assignment rather than an equality test - unlike Visual Basic, if that is where you're coming from, the two have different symbols.
That should thus be:
if (Letter == 'P')
Related
This question already has an answer here:
C++ string and string literal comparison
(1 answer)
Closed 1 year ago.
Question - The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.
Input -
The first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.
Output -
If the word t is a word s, written reversely, print YES, otherwise print NO.
When I write this code, the output is wrong -
int main(){
char s[100000],a[100000];
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
But when I write this code, the output is correct -
int main(){
char s[100000];
string a;
cin >> s >> a;
strrev(s);
if(s==a){
cout << "YES";
}else{cout << "NO";}
}
Why is it like this, is there a rule that a character array cannot be compared to another character array and if so, how can it be compared to a string?
Remember that arrays naturally decay to pointers to their first elements, and it's such pointers that you are comparing.
In short, what you're really doing is:
if(&s[0] == &a[0])
And those two pointers will never be equal.
To compare the contents of character arrays, you need to use strcmp() or similar function instead, eg:
if(strcmp(s, a) == 0)
Since you're programming in C++, please use std::string for all your strings. There are overloads for the == operator that do the right thing if you have std::string values.
This question already has answers here:
No match for 'operator==' C++ compile error
(3 answers)
Closed 2 years ago.
I have been trying to make a password hash simulator which hashes passwords, and when I try to run it with this if statement:
if (password == letters[just]){
justtwo++;
cout << letters[just]
}
It works perfectly fine, but if I put:
if (password[justtwo] == letters[just]){
justtwo++;
cout << letters[just]
It says:
no match for 'operator=='
Even though I didn't put operator== anywhere.
(BTW, I am putting justtwo to see if I can isolate the letters of the password so I can add a list that changes those letters into random gibberish)
I don't know why it does this, but it does. BTW, it's my first time here, so I'm kind of a noob to this website, and this is my first ever C++ program.
If anyone is curious, here is the code. The reason for all the random words is because they are placeholders, and when I figure everything out I will put what actually goes there. :)
string letters[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
string password;
cout << "lol:";
cin >> password;
bool white = true;
int just = -1;
int justtwo = 0;
while (white){
just++;
if (password[justtwo] == letters[just]){
justtwo++;
cout << letters[just];
}
}
cout << "lol";
return 0;
}
it says "no match for 'operator==' " as an error even though I didnt put operator== anywere.
Ah, but you did! In c++, A == B is shorthand for the function operator==(A,B) (or, if A is an object, A.operator==(B)). This is how operator "overloading" works. It allows you, the programmer, to define what the equals operator means when called on two user-defined objects (or a user-defined object and plain old data, or whatever). What you wrote:
if (password[justtwo] == letters[just]){
translates to:
if (operator==(password[justtwo], letters[just])){
The left-hand operand is actually a char, because the string class defines another operator called operator[](size_type pos) which returns the character at the given position. You are trying to compare a char to a string, and that operation is not defined.
The reason the first version you wrote works is because both the left-hand and right-hand operands of the == are string objects:
string letters[] = ...; // letters is an array of string objects
string password; // password is a string
if (password == letters[0]){ // letters[0] is a string
...
If you take a look at the documentation of the std::string class, you'll see that there is an operator==(string, string) method defined.
You have a few options for fixing this code. You can just make letters a string instead of an array of strings:
string letters = "abcdefghijklmnopqrstuvwxyz";
That way, when you write password[justtwo] == letters[just], you are comparing a char with a char, which is a defined operation.
Another way of fixing the code is to make letters an array of chars:
char letters[] = {'a', 'b', 'c', ...};
This gets you to the same result as above. You could also use a c-style char * and achieve the same results.
Finally, if you want to be really tricky (I do not recommend doing this, however), you can define an equality operator between a char and a string like this:
bool operator==(const char& lhs, const std::string& lhs){
return rhs.size() == 1 && rhs[0] == lhs;
}
The type of letters is array of string. So the the type of letters[just] is string.
And the type of password is string.
So the first version of the code works.
if (password == letters[just]){
justtwo++;
cout << letters[just]
}
And the type of password[justtwo] is const char& (As you are new to C++, you can consider it as char for now).
The compiler throws the error as the type of password[justtwo] is different from letters[just].
This compares a std::string with std::string (implicitly converted from const char*), which is a valid comparison:
password == letters[just]
This compares a const char with std::string, and that's not a valid comparison:
password[justtwo] == letters[just]
If you want to compare a substring, you'll need to ask for it:
password.substr(justtwo, 1) == letters[just]
Of course you don't need std::string here, you could either use an array of characters, or you could use a singular string and compare character to character:
string letters = "abcd...xyz";
Then you can easily compare one to another as const char vs. const char:
password[justtwo] == letters[just]
Variable password is of type std::string and letters is of type vector of strings. So when you compare
if (password == letters[just])
you are comparing string to another string because [..] takes out one value from letters which is actually a string.
But when you write condition as
password[justtwo] == letters[just]
what you end up comparing is a single character with another string. This part password[justtwo] will take out a single character out of password variable since it's a string of characters.
The error message signifying usage of operator== is just your usage of == operator.
Maybe you want to store actual letters in variable letters? Then use a vector<char> letters = {'a', 'b'}. Then your second condition will run fine because you will be comparing character to another character.
Problem Solved: StringVariable[position] (in this case Word[e]) outputs a value that is defined as a char variable type rather than the string variable type I had expected it to. Thank you all for your help!
When I run my Hangman game I get the following error:
Error 2 error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
Error 1 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
4 IntelliSense: no operator "!=" matches these operands
3 IntelliSense: no operator "==" matches these operands
I commented in the code where this error points to and copied in the functions related to the problem. The functions were then run in the main() function to simplify the code.
This section of the code is meant to check if the guess is equal to the letter in the word. Let me know if I need to provide further explanation.
Related Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Functions
void GrabWord();
void DiscoverLet();
void guess();
//Variables
int NumL, Fl, F, count[10];
string G, Word;
//Grab Word from .txt and define NumL
void GrabWord()
{
//Grab Random Line from .txt
//Random Line >> Larray
Word = "short";
NumL = Word.size();
}
//Checks if Guess matches any letters
void DiscoverLet()
{
for(int e = 0; e < NumL; e++)
{
//Error Points to the following two comparisons
if(G == Word[e])
{
count[e] = 1;
}
else if(G != Word[e])
{
Fl++;
}
else
{
cout << "Error: DiscoverLet(), G to Word[]\n";
}
}
if(Fl == NumL)
{
F = F + 1;
}
Fl = 0;
}
The proper string comparison that you are looking for is called find:
if(Word.find(G) > std::string::npos)
{
count[e] = 1;
}
else
{
Fl++;
}
The reason why your comparison does not work was that you Word[e] was grabbing a character of the string and it was being compared to a string variable.
Judging by your code it looks like you wanted to count the number of times the letter appears in the string. If you wanted to count the number of times the letter appears in the string then you can use the find function like this:
int count = 0;
int foundIdx = 0;
for(int i = 0; i < NumL; i++)
{
foundIdx = Word.find(G, foundIdx+1);
if (foundIdx == std::string::npos)
{
break;
}
count++;
}
if(G == Word[e])
...
else if(G != Word[e])
In these comparisons, G is a string and Word[e] is a character in a string. There is no operator to perform the respective comparisons.
G is a variable of type string. Word is also a type of string. So as you might already know that strings are nothing but array of chars. So Word[e] points to a character of the Word string. So
if(G == Word[e])
Here, you are comparing a string with a character. But C++ has no idea how to do that! I mean C++ does not know how to evaluate the expression. Because the operator == for comparing a string and a char is not overloaded inside string class. Same goes for the line
if(G != Word[e])
If you're trying to find out if Word[e] character appears in the G string, you should run another loop searching character by character of the string G. Or you can use find function.
The reason of the error is because you are comparing string to a character. You can use ==, !=, >, <, etc on character, but certainly not strings. And also, the string G appears to be empty. Hope this helps and correct me if I'm wrong! Happy coding!
G is string type but Word[e] is char type. You should convert Word[e] to String to compare with G by std::to_string or use method string::find with G to find content Word[e] in G.
The comparison won't work that way. You need to understand what is the difference between a char and a std::string. A variable of type char represent a single letter. A char cannot be multiple character, and cannot be empty. Is strictly one, single letter. Nothing less, nothing more.
A std::string can be seen as a managed array of char. It's size can be 0 to very big. This type expose the array access operator, the [n], and that operator returns a character from the string at position n. It's return type is char.
Since G is supposed to be an input letter from the user, I'd suggest you to declare G as a char. In fact, it will solve your problem.
The reason for that a string cannot be compared to a single character. A string is designed to be comparable to another whole string. And a character can be compared with another integral, or put it simpler, another char. So if you change the type of G to char, your comparison will work as expected.
There is a part of a code for "making the first letter of each word capitalized" I dont understand.
http://www.cplusplus.com/forum/beginner/117463/
std::string str = x;
str [0] = toupper (str[0]);
std::for_each(str.begin()+1, str.end(), printChars);
std::cout << str;
return 0;
}
Void printChars(char& c)
{
if( (*(&c - sizeof(char))) == " ")
c = toupper(c);
}
I understand it sets the first letter to capital always, and checks for each one in the string after.
But why does he use if((*(&c - sizeof(char))) == " ") and how does the * , & and setting it to blank work in this case?
how does ... work in this case?
It does not work. The program that you show is ill-formed and is not likely to compile.
Void printChars(char& c)
There is no type Void in C++. I suspect that you intended to write void instead.
(some_char_value) == " " // expression simplified by me
You may not compare a character to a string literal.
But why does he use if((*(&c - sizeof(char))) == " ")
He doesn't. He uses if( (*(&c - sizeof(char))) == ' ').
how does the & work in this case?
It is the address-of operator. It is used here to get a temporary pointer to the memory address of c.
how does the * work in this case?
It is the indirection operator. It is used here to get the character at the memory location &c - 1. Which is a character in str right before the character referred to by c.
and setting it to blank work in this case?
He doesn't set anything in the quoted expression. == is the equality comparison operator. He compares the values of the &c - 1 and the character literal ' '.
In english: He tests whether the character before c is space. In other words: He test whether c is the first character of a word.
This code is performing simple pointer arithmetic. The code you are asking about is using the reference operator & to grab the address of the variable c. Then performing subtraction of the size of a char to check if the char before c is a space if so it calls toUpper(). So for example
if the address of c is 100 then &c - sizeof(char) is checking the char at address 99 then the * is used to dereference the variable which allows for the comparison of the variable using == " ".
I'm asking the user for an input, but I want the question to stay on screen until the input meets one of the allowed inputs. Here's my code
string input = "";
string departure = "";
cout << "Please enter an airport code: ";
do
{
getline(cin,input);
stringstream(input) >> departure;
} while(departure.compare("MAN") != 0 || departure.compare("EMA") != 0 || departure.compare("LHR") != 0 );
}
I want it to loop until the user enters MAN or EMA or LHR; also if they are lowercase I would like for it to be accepted aswell.
Every time I run this, even if I enter a correct input, it just keeps taking words in and doesn't do anything else.
The condition
departure.compare("MAN") != 0 || departure.compare("EMA") != 0 || departure.compare("LHR") != 0
is always true, regardless of what departure is.
compare returns 0 on equality. So what you're basically telling the compiler is
Run the loop while departure is different than "MAN" OR different than "EMA" OR different than "LHR".
You need && instead of || in your condition.
This condition always returns true since it can't not be all 3 at once.
The && will return false as soon as the input is one of the 3 accepted.
Consider using boost::to_upper to convert the input into upper case before you perform the comparison in the while(...) statment. This will resolve the lowercase/uppercase issue.
http://www.boost.org/doc/libs/1_41_0/doc/html/boost/algorithm/to_upper.html
Also, when dealing with C++ strings, I recommend you simply do
departure == "MAN" || departure == "EMA" || departure == "LHR"
You don't need to do string.compare in C++, unlike some other languages (for example Java), as the == operator is overloaded to compare the /content/ of the string, rather than the string object itself.
Also somebody else beat me to it about the compare method returning 0 when equal.
First Your conditional for the while loop is incorrect. Right now it reads, while departure is not 'MAN' or is not "EMA" or is not "LHR", continue looping. Because departure cannot be all three of them simultaneously, the loop never ends. I would suggest replacing your OR's (||) with AND's (&&)
As well, each execution of the loop you need to clear the value in departure, otherwise the previously entered lines persist and your comparison will fail even when a correct airport code is entered.
our main problem is that the string is being compared incorrectly. Let's say we type in "MAN".
The departure.comare("MAN") != 0 will be true if the string is not "MAN". Fine, we typed in "MAN", so it's false. Now we OR that with departure.compare("EMA") != 0 - which is true, because "MAN" is not equal to "EMA". So you need to combhine your condition with &&, not ||.
To fix for "owercase", there are two choices. Either convert the input string to uppercase, or compare with all different combinations of lower and upper case (Man, MaN, mAn, etc) - the latter gets very tedious very quickly.
Have a look at this one for some options of comparing strings in a case-insensitive way:
Case insensitive string comparison C++