Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

problem loading numbers into array

grepawk

New Coder
Hello
i am trying to make code which will request user for his phone number (on one line), that number will be stored in array number, everything works ok till i dont type less then 10 numbers and press enter, cycle is waiting for next number/s on new line but i want program to give message like: number is too short or too long , type that number again: i have tried many options with while cycle and do while but none of them works properly

#define ARRAYSIZE(a) (sizeof(a) / sizeof(a[0]))
int main()
{
int number[10];
printf("type your number: \n");
for (int i = 0; i < ARRAYSIZE(number); i++)
{
scanf("%1d",&number); //fe input: 033232313 is correct
//123 is incorrect user will be able to type numbers again
}
...
}


Thanks in advance for any help...
 
It seems you are trying to read each digit from the keyboard separately, using scanf. Not a great idea for a number of reasons. I never use scanf for keyboard input. Moreover, your code is dubious. It may seem to work, but as per the man page, the argument should be a pointer to an int, not a pointer to the entire array. Why do you want the digits in an array of integers anyway ? Are you going to do arithmetic with them ?

May I suggest the following approach :
1) Read one line from the keyboard, to a maximum of 10 characters. The statement to use is fgets(buffer, MAXDIGITS+1, stdin)
2) Loop through the characters in buffer, checking that each is a digit (maybe allow space, + and - also) and that the nr of digits is between min and max.

This gives you control control and flexibility and allows you to give very precise error messages. But note that the fgets will let you type in excess of 10 characters, as it has to wait for an enter.
For even greater control, consider a loop around getchar(). That way you can examine each character immediately, and break the loop when the maximum is reached.

I hope this helps some.
 
Back
Top Bottom