It can be challenging specially that you're still in the first few weeks. There are many I/O functions in the C standard library that you can use for that purpose. One of them is fgetc
. Execute man fgetc
in the terminal for more info on that function!
The approach could be as follows:
// read number
1. declare a string called num // make sure it's big enough to hold the max number
2. while (true)
3. read the next character and store it into a char variable called c
4. if c is a newline character or there's no more room in num
5. terminate num // put a null character
6. break
7. append c to the current value of num
// validat input
8. if num[0] isn't a '-', a '+', or a digit
// handle invalid input
9. for (i = 1 to i < the length of num, increment i by 1)
10. if i isn't a digit
// handle invalid input
11. break
you may use a function like atoi
to convert the string then to an integer. Execute man atoi
in the terminal for more info on that!
This approach is fairly close to what GetInt
uses. There's an easier approach using a function like scanf
, but this approach will require you to learn more about that function.