2

I am trying to iterate over a string to see if the input is a whole number.

This is the code:

 for (int i = 1; i < strlen(buffer); i++) //Checking that each character of the string is numeric
    {
        if (!isdigit(buffer[i]))
        {
            valid = false;
            break;
        }
    }

    if(valid == false)
    {
        printf("Invalid input!");
    }

    else
    {
        num = atoi(buffer);
        printf("The number entered is %d", num);
    }

The problem is that even if the input is correct, let us say 2, the output message is still "Invalid input!".

I am very frustrated right now. I have tried using the atoi function, the strtol function and other methods so that I can validate a number and ensure that:

1) it is not a letter 2) it is a whole number

Please help me. I have been trying to solve this problem for over 2 hours.

6
  • you need to post your isdigit code Commented Mar 5, 2013 at 18:05
  • the isdigit is a method provided by the ctype.h library. I did not create it myself Commented Mar 5, 2013 at 18:07
  • This is obviously not too localized. The code snippet is obvious, the output is unexpected though. Commented Mar 5, 2013 at 18:11
  • Reading man pages helps. As well as learning how to use a debugger. Commented Mar 5, 2013 at 18:14
  • 1
    And it's still int main(void). Commented Mar 5, 2013 at 18:18

1 Answer 1

8

Since fgets reads a line, a '\n' (which is not a digit) may remain at the end of your string. You can remove it:

#include <string.h>

char *pend = strrchr (buffer, '\n');

if (pend != NULL) *pend = '\0';
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much Kirilenko :))) It solved the problem completely. What is the code doing exactly. Is it replacing \n with \0?
Thank you so much. So pend is a data pointer to the null-terminating character and if pend is not null (null-terminating character found), it replaces it with \0?
It replaces the last newline character of the string with a \0. If no newline character is found, dereferencing pend would lead to undefined behavior, so we avoid such case.
Thanks again :) Sorry if I ask such questions but I am kind of new to C.
@Matthew: No need to be sorry. If the question is well-asked, it's a pleasure to answer. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.