I am facing a error when compiling my c++ code,
when hovering over it, it says error:-
no operator ">=" matches these operands -- operand types are: std::__cxx11::string >= intC/C++(349).
the code goes like this, its a function in a structure, which takes an array variable from the same structure and runs a loop to check the values in that array is greater or equal to 999,
ERROR IS ON THE LINE - if ((PowerChecker.cpower[a] >= 999))
I AM NOT ALLOWED TO COMPARE ARRAY
customers InputChecker(struct customers PowerChecker)
{
for (int a = 0; a < 4; a++)
{
if ((PowerChecker.cpower[a] >= 999))
{
cout << "Please re-specify the power of your character" << PowerChecker.cpower[a] << endl;
cout << "Power shoudl not Excced Limit 999 " <<endl;
}
}
return (PowerChecker);
}
here is the image of error after compiling
EDIT: SOLVED
As Peter and drescherjm wrote in the comments, it seems that you try to compare a string to an integer. You will need to convert the string first. Many ways how to do this can be found here: How can I convert a std::string to int?
Related
In short I am getting different output for string comparison using string::compare() vs relational operator '<' on std::string class objects.
string str = "100";
cout << str.compare("10")<<endl; //prints 1
cout << ("100" < "10") <<endl; //prints 1
Here's the demo url
lexicographically "100" is greater than "10" and hence ("100" <"10") must print 0 since it's false but the output 1 i.e true is not expected.
The str.compare() function returns > 0 which is expected validating "100" > "10".
Why is this happening?
In this statement
cout << ("100" < "10") <<endl;
you are comparing two pointers of the type const char * to which the used string literals are implicitly converted. The result of such a comparison is undefined (At least in the C Standard there is explicitly stated that such operation is undefined).
In fact the above statement is equivalent to
cout << ( &"100"[0] < &"10"[0] ) <<endl;
If you want to compare strings the you need to write at least like
cout << (std::string( "100" ) < "10") <<endl;
In this case the output will be
0
Pay attention to that according to the C++ 20 (7.6.9 Relational operators)
...The comparison is deprecated if both operands were of array type prior to these conversions
And the both string literals prior to comparison have array types.
I'm working on a midterm project for my coding class, and while I've gotten the majority of kinks worked out I'm struggling with comparing two string values and determining if they are equal or not. The strings in question are ANSWERKEYand studentAnswers. The former is a constant that the latter is compared to.
The code in question is as follows.
if (studentAnswers == ANSWERKEY)
{
percentScore = 100.0;
cout << "Score: " << percentScore << " % " << 'A' << endl;
}
else if (studentAnswers != ANSWERKEY)
{
int count = 0;
double answerCount = 0.0;
while (count < ANSWERKEY.length())
{
if (studentAnswers.substr(count, count+1) == ANSWERKEY.substr(count, count+1)
{
answerCount++;
count++;
}
else
{
cout << "Incorrect answer." << endl;
count++;
}
}
percentScore = ((answerCount) / (double)ANSWERKEY.length()) * 100.0;
cout << "Percent score is " << percentScore << "%" << endl;
}
The exact issue I'm facing is that I can't work out a better way to compare the strings. With the current method, the output is the following:
The intro to the code runs fine. Only when I get to checking the answers against the key, in this case "abcdefabcdefabcdefab", do I run into issues. Regardless of what characters are changed, the program marks roughly half of all characters as mismatching and drops the score down because of it.
I've thought of using a pair of arrays, but then I can't find a solution to setting up the array when some values of it are empty. If the student's answers are too short, e.g. only 15 characters long, I don't know how to compare the blank space, or even store it in the array.
Thank you for any help you can give.
First:
if (studentAnswers == ANSWERKEY)
{...}
else if (studentAnswers != ANSWERKEY)
{ ...}
looks like an overkill when comparing strings. And where is the else part ?
Second, this is risky. Read the IEE754 and articles about cancellation, or even SO:
double answerCount = 0.0;
...
answerCount++
Third:
You are checking character by character using substr. To me it feels like using a hammer to kill a bacteria.
studentAnswers.substr(count, count+1) == ANSWERKEY.substr(count, count+1)
Fourth:
What if studentAnswers is shorter than ANSWERKEY ?
Conclusion:
You need to clarify inputs/expected outputs and use the debugger to better understand what is happening during execution. Carefully check all your variables at each step fo your program.
I am trying to learn c++ and one of the assignments is to ask the user for a letter - then ask for a string of text and count how many times the 1st letter is repeated in the string of text.
I have written some code that successfully gets to the point of asking for the letter & the string of text - I can display both
I can traverse the string of text counting how many letters there are in the string. When I try to add an if check to compare the current letter in the string inside the loop with the letter 1st asked for - I get this compile error:
error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
if (textToCount[i] == letterToCount)
this is the full code I have written
char getLetterToCount(char letterToCount[]);
char getTextToCount(char textToCount[]);
int countLetters(char letterToCount[], char textToCount[]);
int main()
{
char letterToCount[1];
getLetterToCount(letterToCount);
char textToCount[256];
cin.ignore();
getTextToCount(textToCount);
countLetters(letterToCount, textToCount);
return 0;
}
char getLetterToCount(char letterToCount[])
{
cout << "Enter a letter: ";
cin >> letterToCount;
}
char getTextToCount(char textToCount[])
{
cout << "Enter text: ";
cin.getline(textToCount, 256);
}
int countLetters(char letterToCount[], char textToCount[])
{
int numChrsInString = 0;
int numTimesChrtoCountrepeated = 0;
for (int i = 0; textToCount[i] != '\0'; i++)
{
if (textToCount[i] == letterToCount)
{
numTimesChrtoCountrepeated++;
}
}
cout << "num chrs in string: "
<< numChrsInString
<< "num times chr counted: "
<< numTimesChrtoCountrepeated
<< endl;
}
I did a fair bit of output to try and figure out what was wrong with these - I pulled the code for that out because it made it a bit more confusing.
BUT the compile error explains what is wrong, I just don't understand why it is wrong because the things I am trying to compare are BOTH text letters...
It would be great if someone who knows c++ can explain what I am doing wrong
You are comparing a char with a pointer to char
Use:
if (textToCount[i] == letterToCount[0])
~~~
Note: There are few obvious nitpicking but above is the main compiler error cause
In C++, arrays are pointers. C++ considers lettertocount to be a pointer because you're passing it as an array. You don't want to pass that; you want to pass just a character:
int countLetters(char letterToCount, char textToCount[])
A bigger question to my mind is, why do you think you have to pass lettertocount as an array? Apparently it's just one letter. When you invoke this function do you eventually want to count multiple letters?
I'm just practicing using arrays. So my program consist of inputting numbers of data type double into the array and have them print out. Simple.
I only limited the numbers down to 4. So the array, num_List[3] is in the code. I've made sure to use the for loops properly for reading and printing out the result.
The first few times I tested the code. I realized that the 4th number in the array was in scientific notation, telling me that I forgot to initialize the array to 0, in this case 0.0, since I'm using double. So I put in this code.
for (index = 0; index <= 3; index++)
num_List[index] = 0.0;
This code should have initialized the arrays of num_List to 0.0. However, when I tested this, nothing came up, after I inputted the 4 numbers. So I made a logical error here or it's something else with the for loop that's causing it to be trapped and not continue the execution.
I've read in the books about this particular way to initialize.
#include <iostream>
using namespace std;
int main() {
double num_List[3]; // These are my variables
int index;
//double num; // Ignore these two for now, for they are to be modified later on.
//double result;
cout << "This program will summarize the numbers you've inputted print out the result. \n";
cout << "And also print out the address of the 1st and 4th address in the array." << endl;
cout << "Please enter the four numbers to be summarized.";
for (index = 0; index <= 3; index++) { // I put this in after I realized my mistake of not initializing my arrays to 0.0.
num_List[index] = 0.0;} // This is where the problem is, I think.
for (index = 0; index <= 3; index++) // This reads in the user the input
cin >> num_List[index];
cout << "The numbers you have inputted is:\n";
for (index = 0; index <= 3; index++) // This prints out the array.
cout << num_List[index] << ", " << endl;
return 0;
}
If you focus on the aforementioned code, and try to compile it, you'll see that my code unfortunately doesn't continue on from there after you input 4 numbers, regardless of whether or type a number and space it up to 4 numbers, or input a number, press the enter key for those numbers. Most likely I've made a obvious mistake, but I'm having some trouble seeing it.
I use Code Blocks, so things are a little different compared to the Bloodshed C++ compiler I used to use to practice codes on.
double num_List[3];
This declares an array with 3 elements, indexed 0 through 2.
for (index = 0; index <= 3; index++)
This loops through 4 indices, 0 through 3. When you do something with num_List[3], you get undefined behavior. In your trial, the undefined behavior fortunately resulted in just some garbage output.
Please keep in mind that I'm extremely new to C++ so the most direct/simple solution (ideally with an explanation) is preferred.
I have three questions about this code that I have quite literally copied from Stroustrup's "Programming: Principles and Practice."
Here is the code:
#include "std_lib_facilities.h" //using this header as it is what the book recommends
int main()
{
vector<string> words;
for (string temp; cin >> temp;)
words.push_back(temp);
cout << "Number of words: " << words.size() << "\n";
sort(words); //"no instance of overloaded function "sort" matches the argument list"
for (int i = 0; i<words.size(); ++i) //'<' : signed/unsigned mismatch -- exe still runs in spite of this, not sure what it means
if (i == 0 || words[i-1]!= words[i])
cout << words[i] << "\n";
keep_window_open(); //added because i don't know how else to keep the window open
}
I'm getting two errors regarding the sort() algorithm:
"error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 1 provided"
"error C2780: 'void std::sort(_RanIt,_RanIt,_Pr)' : expects 3 arguments - 1 provided"
I've searched for both of these online but haven't come across an answer that makes sense to me.
Second, I'm curious about the
'<' : signed/unsigned mismatch
because it does not stop the program from running. If the answer to this question is too complex for a beginner then feel free to skip it, I'm just interested.
I would suggest checking out what Joachim linked to and http://www.cplusplus.com/reference/algorithm/sort/. When calling sort you must provide it an iterator to start at and an iterator to end at, with an optional third argument that can be your comparison operator.
Below is an example that I made from your code;
#include "std_lib_facilities.h" //using this header as it is what the book recommends
int main()
{
vector<string> words;
for (string temp; cin >> temp;)
words.push_back(temp);
cout << "Number of words: " << words.size() << "\n";
sort(words.begin(),words.end()); //beginning and ending of where you want to sort
for (uint i = 0; i<words.size(); ++i) //'<' : //changed int to uint
if (i == 0 || words[i-1]!= words[i])
cout << words[i] << "\n";
keep_window_open(); //added because i don't know how else to keep the window open
}
As for the signed/unsigned error, ints are signed meaning that they can be negative, so they can be −32,768 to 32,767, where as uints are unsigned meaning that they can be 0 to 65,535.
The code can still work but beware that if word.size() is larger than 32767 and i is an int then i will never grow to be larger than word.size(). i will simply wrap around to -32768 when incremented past 32767. I would suggest using uint as the type of i.