0

I'm making a program where the user inserts their phone number and store it in a text file. But I would like to insert a feature where only numbers are allowed.

How can I do it?

Code:

#include <stdio.h>
#include <stdlib.h>

int main ()
{
   FILE *f;
   char telefone[10]];
   int len;
 

   do{
   printf("\nTelefone:");
   gets(telefone);
   len = strlen(telefone);
   }while(len <= 0 || len > 10);


    return 0;

   f = fopen ("ricardo_duarte.txt","w");
  
   fprintf (f, "\nTelefone: %s\n",telefone);

   fclose (f);
   return 0;
}
  • You'd have to verify that the string contains nothing but digits after reading it, and display a message if it has anything else. – SergeyA Apr 26 '21 at 15:37
  • It is called "input validation". You go over the input string and check each character to be a valid digit. If they are not, you ask the user to input again. Don't use `gets` BTW... – Eugene Sh. Apr 26 '21 at 15:38
  • If your program reads the phone number as a string, then your only option is to check the string afterwards (check every character) and handle invalid input, e.g. by showing an error message and asking the user to enter a correct value. Or use a library that allows unbuffered input character by character and filter out invalid characters. (e.g. curses) – Bodo Apr 26 '21 at 15:38
  • Hint: use the `isdigit()` function. – Christian Gibbons Apr 26 '21 at 15:40
  • ok i think i got it guys ty :) – thomas turbating Apr 26 '21 at 15:42
  • IMO, the cleanest option is [`strtol`](https://linux.die.net/man/3/strtol). If the string is all numbers, `*endptr` will always be 0 and it would save you the pain of making a whole `isdigit` loop. – mediocrevegetable1 Apr 26 '21 at 15:45
  • Obligatory: [Never use gets()!](https://stackoverflow.com/q/1694036/10077) – Fred Larson Apr 26 '21 at 16:05

1 Answers1

0

You could parse input with scanf by limiting it only to digits:

scanf("%[0-9]", telephone);

I suggest to limit the scan length to the buffer size to avoid buffer overflows.

char telephone[10 + 1]; // 10 digits + NUL-terminator
scanf("%10[0-9]", telephone);
tstanisl
  • 13,520
  • 2
  • 25
  • 40