template<int (&F)(int)>
int safe_ctype(unsigned char c) { return F(c); }
//...
char c = CHAR_MIN;
bool b = safe_ctype<isupper>(c); // No UB.
std::string s = "value that may contain negative chars; e.g. user input";
std::transform(s.begin(), s.end(), s.begin(), &safe_ctype<toupper>);
// Must wrap toupper to eliminate UB in this case, you can't cast
// to unsigned char because the function is called inside transform.
int ord(char c) { return (unsigned char)c; }
char chr(int n) {
assert(0 <= n); // Or other error-/sanity-checking.
assert(n <= UCHAR_MAX);
return (unsigned char)n;
}
// Ord and chr are named to match similar functions in other languages
// and libraries.
char* something = "123456";
int number = parseInt(something);
...这招对我很管用:
int parseInt(char* chars)
{
int sum = 0;
int len = strlen(chars);
for (int x = 0; x < len; x++)
{
int n = chars[len - (x + 1)] - '0';
sum = sum + powInt(n, x);
}
return sum;
}
int powInt(int x, int y)
{
for (int i = 0; i < y; i++)
{
x *= 10;
}
return x;
}
/* chartoint: convert char simbols to unsigned int*/
int chartoint(char s[])
{
int i, n;
n = 0;
for (i = 0; isdigit(s[i]); ++i){
n = 10 * n + (s[i] - '0');
}
return n;
}
long long ChardToint(char *arr, size_t len){
int toptenf=1;
long long toptenLf=10000000LL;
long long makeintf=3000000000000;
makeintf= 0LL;
int holdNumberf=0;
for(int i=len-1;i>=0 ;i--){
switch(arr[i]){
case '0':
holdNumberf=0;
break;
case '1':
holdNumberf=1;
break;
case '2':
holdNumberf=2;
break;
case '3':
holdNumberf=3;
break;
case '4':
holdNumberf=4;
break;
case '5':
holdNumberf=5;
break;
case '6':
holdNumberf=6;
break;
case '7':
holdNumberf=7;
break;
case '8':
holdNumberf=8;
break;
case '9':
holdNumberf=9;
break;
default:
holdNumberf=0;
}
if(toptenf>=10000000){
makeintf=makeintf+holdNumberf*toptenLf;
toptenLf=toptenLf*10;
}else{
makeintf=makeintf+holdNumberf*toptenf;
toptenf=toptenf*10;
}
}
return makeintf;
}