loops – using isDigit to find charecters c++
loops – using isDigit to find charecters c++
Below I modified your code so that it gives correct answer. For input 30-something
it gives 36
as output.
As I understood you want to finish conversion right after 30
i.e. ignore -something
. For such behaviour I put a flag stop_on_first_non_digit
in my code, if it is true
then it finishes on first non-digit character. But you may set it to false
then I just skip non-digit chars but use all chars that are digits, for example -something
has e
in it, so contains one digit, if stop_on_first_non_digit
is false
then this single e
digit will be used. By default now it is true
so that it behaves the way you like.
Also I kept your logic of skipping first spaces in a string so you can input 30-something
(leading spaces) and it gives 36
too.
#include <string>
#include <cctype>
#include <iostream>
int main() {
std::string duo = 30-something;
bool stop_on_first_non_digit = true;
size_t i = 0;
int decValue = 0;
while (i < duo.length() && std::isspace(duo.at(i)))
++i;
for (; i < duo.length(); ++i) {
char c = duo.at(i);
int digit = 0;
if (std::isdigit(c))
digit = c - 0;
else if (c == x || c == X)
digit = 10;
else if (c == e || c == E)
digit = 11;
else {
if (stop_on_first_non_digit)
break;
else
continue;
}
decValue *= 12;
decValue += digit;
}
std::cout << decValue << std::endl;
}
Output:
36