Part of my program asks the user to input a number between 1 and 100.
If the number is not between 1 and 100, the program displays an error and asks them to re-enter the number.
I want it set as a string, especially so that if they enter a letter, the program will continue to function correctly.
The problem is that the compiler does not like that I'm using the greater than/less than operators to compare strings. It is fine if I use them for integers, but for strings, it gives me an error.
The error is:
no match for 'operator<' in 'number < 0'
Can anyone offer insight on how I can successfully compare strings? Thank you.
1 2 3 4 5 6 7 8 9 10 11 12 13
int compare(string number)
{
while (number < 0 || number > 100)
{
system("CLS");
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n";
cout << "\t\t\t\t "
<< number << " is invalid!";
cout << "\n\t\t Please enter a value in the range 1-100: ";
cin >> number;
cout << "\n\n\n\n\n\t\t";
}
}
#include <iostream>
#include <string>
#include <stdlib.h>
usingnamespace std;
int compare(int number)
{
//loop until a valid score is entered...
while (number < 0 || number > 100)
{
system("CLS");
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n";
cout << "\t\t\t\t "
<< number << " is invalid!";
cout << "\n\t\t Please enter a value in the range 1-100: ";
cin >> number;
cout << "\n\n\n\n\n\t\t";
}
}
int main()
{
int number;
cout << "Enter a number between 1 - 100: ";
cin >> number;
compare(number);
}
A C++ string can be compared with the == operator, as well as the < and > operator. However, they can only be compared with other strings; you are comparing a string to a number, unless you write your own operators for what you want to do.
However, since you're examining a number, why not make number an int, rather than a string? Then you can use the < and > operators as you are at the moment.
@mobat, compare should return an integer.
@neowoot, You can't compare a string and an integer (this isn't the same as comparing strings). You should probably use an integer as @mobat did but you can still get a string from the input and use a string for other functions, just convert the input from string to int[1] before giving it as a parameter to compare.
This function returns 0 if the two strings are the same, greater than 0 if the string being compared is greater than the string given as parameter and vice-versa.
I hope this helps!
EDIT: I might have misinterpreted the question.
You may want to convert the string into an integer then use this integer with the <> symbols.
Although I've not tried it, I have a sneeky suspicion that the string::compare(...) method will work but you'll have to test it for yourself and see.
Example:
1 2 3 4
while ( number.compare("0") > 0 || number.compare("100") < 0 )
{
//your code here
}
FWIW, you actually can compare two strings as numeric values, so long as they have the same sign and the same number of digits (add leading zeros as needed).