Question
Problem 2: Write a function read_int that mimics system call 5 (but only for non-negative integers). The function needs no input parameters but should return
Problem 2: Write a function read_int that mimics system call 5 (but only for non-negative integers). The function needs no input parameters but should return the integer generated by the user key presses (appropriately stored onto the stack). To read in an integer, your function should listen for and read in MMIO keyboard inputs until either (a) the user hits the enter key or (b) 10 characters have been exceeded [since the largest possible signed 32 bit integer is 2147483647, which has 10 characters]. If the user inputs an invalid character such as a letter (e.g., a) or symbol (e.g., $), your function should return -1 to indicate that an invalid number has been entered. Along the same lines, if the user tries to enter a negative number (e.g., contains - character) or too large of a number (i.e., causes overflow), also have your function return -1. Lastly, if the user types no characters at all and hits the enter key, return -1. Here are some examples that you can use as test cases:
User Types: 1 2 3 4 ENTER Return: 1234
User Types: 0 ENTER Return: 0
User Types: 5 3 g 9 4 ENTER Return: -1 # invalid character g
User Types: - 3 8 ENTER Return: -1 # invalid character -
User Types: 9 7 3 5 9 1 8 3 5 8 Return: -1 # overflow
User Types: 1 2 3 4 5 6 7 8 9 0 Return: 1234567890 # not overflow
User Types: ENTER Return: -1 # user did not enter any digits
Hint: You will need to refer to an ASCII table to figure out mappings between digit characters ASCII values and their corresponding numeric values. You will also need this table to determine which characters are invalid. You can find an ASCII table in the back of the textbook or you can simply Google it.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started