AscToInt
The task was to write a function int AscToInt(const char *num); that converts a string from the user’s input, presumably containing numbers, to an actual integer as its return. A string might be either positive or negative (e.g.”-123123” or “+234234” or “989”). If input string contains an alphabetic character or symbol different from “+” or “-” the function is to return 0. Here’s my pretty easy solution: #include <iostream> #include <cstring> #include <cstring> #include <cmath> using namespace std; int AscToInt(const char* num) { int converted = 0; char *str; bool negative = false; int i = 0; if (num[0] == '-' || num[0] == '+') { if (num[0] == '-') { negative = true; } for (i = 0; i < strlen(num); i++) { str[i] = num[i+1]; } str[i] = '\0'; } else { strcpy(str, num); } for (i = 0; i < strlen(str); i++) { if ( (str[i] <= '0' || str[i] >= '9') && !negative) { converted = 0; break; } converted += pow(10, (strlen(str) - 1) - i) * (str[i] - '0'); } if(negative) { converted = -abs(converted); } return converted; } int main() { char* str; int num = 0; cout<< "enter string containing numbers: "; cin >> str; num = AscToInt(str); cout << num; return 0; } It’s kind of a challenge with some benefits for the winners. The function above handles positive and negative numbers and declines inappropriate input. The only thing I haven’t implemented here is that it doesn’t check the length of the input string which can be damaging, but it’s not a part of a task. BTW: haven’t been touched C/C++ since last December cos I didn’t have a challenge!











