0

I am doing greedy, and I want to write a code which says that if the input is not a number, I say something other than it is a number. I know that it is not required, but I just want to know if there is a method of writing the code.

basically

if ( numberEntered < 0 || numberEntered != **(something here to identify that the input is a number)**
{
 blah blah blah, code here. Ignore this part
}
1

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.

3
  • so there is no "int, float, string, etc." identifier? – BooFluff May 19 '15 at 1:53
  • @BooFluff this is pseudocode not actual C code. – kzidane May 19 '15 at 15:11
  • What I was asking is for a C code that would identify data types – BooFluff May 21 '15 at 0:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .