You probably know the following problem: You have written a small program that runs in your console and want the user to enter something. of course, it is very inconvenient when the user types the wrong things, so we have to prepare for any small child hacking like a madman on the keyboard.
Most functions wait for a valid input, which results in the problem that nasty line breaks occur when the user ONLY presses the enter key.
the problem is also normally easy to solve under Linux: read a character with getchar
, determined the position of the cursor with the ANSI escape sequences and provided the whole thing with a do while loop.
BUT: I was not able to find a simple function to read in numbers in the same elegant way. The function must be able to read in numbers, but also be able to prevent line breaks. to achieve this, I used getchar
and store the characters in a char array, whose indices I then convert to the corresponding numbers, which I then add to the actual number.
But maybe there is an easier way? or you have ideas how to optimize the function?
#include <iostream>
#include "TheGameHeaders.h"
#define CLEAR_LINE printf("\033[K")
#define POSITION(Ze, Sp) printf("\033[%d;%dH", Ze, Sp)
#define CLEAR printf("\033[2J")
int getint(int pos_ze, int pos_sp, int qntty_of_incs)
{
int i = 0;
char fake_nbr;
char fake_nbrs[qntty_of_incs];
int real_nbr = 0;
int real_nbrs[qntty_of_incs];
do
{
POSITION(pos_ze, pos_sp);
while((fake_nbr = getchar()) != '\n')
{
if(fake_nbr == '0' || fake_nbr == '1' || fake_nbr == '2' || fake_nbr == '3' || fake_nbr == '4' || fake_nbr == '5' || fake_nbr == '6' || fake_nbr == '7' || fake_nbr == '8' || fake_nbr == '9')
{
if(i <= (qntty_of_incs-=1))
{
fake_nbrs[i] = fake_nbr;
i++;
qntty_of_incs++;
}
else
{
return 1;
}
}
else
{
return 0;
}
}
}
while(i < 1);
for(int a = 0; a < i; a++)
{
fake_nbrs[a] -= '0';
real_nbrs[a] = fake_nbrs[a];
}
int i_fix = i;
int i_fix_2 = i-=1;
for(int a = 0; a < i_fix; a++)
{
i = i_fix_2;
real_nbrs[a] *= pow(10, i-=a);
}
for(int a = 0; a < i_fix; a++)
{
real_nbr += real_nbrs[a];
}
return real_nbr;
}
oh and pow
is a simple function:
int pow(int base, int exponent)
{
if(exponent == 0)
{
return 1;
}
exponent -= 1;
int fixBase = base;
for(int i = 0; i < exponent; i++)
{
fixBase *= base;
}
return fixBase;
}
#include <iostream>
at the top (for no good reason anyway, because it’s never used). You might as well putimport sys
at the top and call it Python. \$\endgroup\$