print ascii code of a character (ktoi)

This commit is contained in:
VaclavT 2021-05-15 00:02:06 +02:00
parent cdfcc753e4
commit 09250861d9
4 changed files with 20 additions and 7 deletions

View File

@ -9,26 +9,34 @@
std::string mini_sprintf_format(bool left_align, bool sign, bool space_on_left, bool padding_by_zero, int width, int precision, int length, char specifier, const MlValue &value) {
std::string s;
std::ostringstream stream_str; // PERF simpler solution..without string stream
bool is_positive = false;
if (specifier == 's') {
return value.as_string();
}
if (specifier == 'c') {
std::ostringstream stream_str;
stream_str << (char) value.as_int();
return stream_str.str();
}
if (specifier == 'i' || specifier == 'd') {
if (value.is_number()) {
int ival = value.as_int();
is_positive = ival >= 0;
s = std::to_string(ival);
} else if (value.is_string()) { // print ascii code of character
if (value.as_string().size() > 0) {
stream_str << (int)value.as_string()[0];
return stream_str.str();
} else {
// TODO handle empty string - error?
}
}
} else if (specifier == 'f' || specifier == 'e') {
double dval = value.as_float();
is_positive = dval >= 0;
std::ostringstream stream_str;
if (specifier == 'f')
stream_str << std::fixed;
else

6
ml.cpp
View File

@ -248,7 +248,8 @@ MlValue MlValue::cast_to_int() const {
return *this;
case FLOAT:
return MlValue(long(stack_data.f));
// Only ints and floats can be cast to an int
case STRING:
return MlValue(std::stol(str));
default:
throw MlError(*this, MlEnvironment(), BAD_CAST);
}
@ -261,7 +262,8 @@ MlValue MlValue::cast_to_float() const {
return *this;
case INT:
return MlValue(float(stack_data.i));
// Only ints and floats can be cast to a float
case STRING:
return MlValue(std::stod(str));
default:
throw MlError(*this, MlEnvironment(), BAD_CAST);
}

View File

@ -40,6 +40,7 @@
))
(defun itok (ascii) (sprintf "%c" (list ascii)))
(defun ktoi (char) (int (sprintf "%d" (list char))))
; pause for interval of seconds
(defun sleep (time)

View File

@ -73,6 +73,8 @@
(ut::define-test "result of (itok 65)" '(ut::assert-equal "A" (itok 65)))
(ut::define-test "result of (itok 48)" '(ut::assert-equal "0" (itok 48)))
(ut::define-test "result of (ktoi \"A\")" '(ut::assert-equal 65 (ktoi "A")))
(ut::define-test "result of (ktoi \"0\")" '(ut::assert-equal 48 (ktoi "0")))
(ut::define-test "result of (write-file \"/tmp/file\" \"write-file test\")" '(ut::assert-equal 1 (write-file "/tmp/file" "write-file test\n")))
(ut::define-test "result of (is-file? \"/tmp/file\")" '(ut::assert-true (is-file? "/tmp/file")))