The input is a string number. How to make a comparison?
3 answers
If I understand you correctly, then you need the following definition of the Check function, as shown in the demo program.
#include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <limits> bool Check( const char *arr, int size, const std::string &CONST ) { return ( CONST.size() < size ) || ( !( size < CONST.size() ) && std::lexicographical_compare( CONST.begin(), CONST.end(), arr, arr + size ) ); } int main() { std::string CONST( "10" ); const char *s = "9"; std::cout << " CONST < s " << std::boolalpha << Check( s, 1, CONST ) << std::endl; s = "10"; std::cout << " CONST < s " << std::boolalpha << Check( s, 2, CONST ) << std::endl; s = "11"; std::cout << " CONST < s " << std::boolalpha << Check( s, 2, CONST ) << std::endl; s = "20"; std::cout << " CONST < s " << std::boolalpha << Check( s, 2, CONST ) << std::endl; s = "20"; CONST = std::to_string( std::numeric_limits<int>::max() ); std::cout << " CONST < s " << std::boolalpha << Check( s, 2, CONST ) << std::endl; CONST = "2147483647"; s = "2147483647"; std::cout << " CONST < s " << std::boolalpha << Check( s, 10, CONST ) << std::endl; CONST = "2147483647"; s = "2147483648"; std::cout << " CONST < s " << std::boolalpha << Check( s, 10, CONST ) << std::endl; return 0; } Output of the program to the console
CONST < s false CONST < s false CONST < s true CONST < s true CONST < s false CONST < s false CONST < s true The function shown does not check if the string contains leading characters '0' . Therefore, a pointer to a string must be passed to the function, starting from a position that does not contain the character '0' , or if the string contains a single character '0'.
|
Maybe here? I just changed more or equal to equal in
if(arr[i] >= CONST[i]-'0') Check. Should work
bool Check(char *arr, int size, const string &CONST){ bool state = false; if(size == CONST.size()){ for(int i=0; i<size-1; i++){ if(arr[i] > CONST[i]-'0'){ state = true; } else{ state = false; break; } } } if(size > CONST.size()) state = true; if(size < CONST.size()) state = false; return state; } |
I need to compare a character array and a string, it should be strictly equal
In my opinion, the easiest way is
bool equal(const char * s1, const string& s2) { return strcmp(s1,s2.c_str()) == 0; } |
-'0'- isnullxbharr[i] == CONST[i]? - isnullxbhCONSTevery time? make itint, and then your code will turn intoatoi(arr) > CONST:) - Harry