My approach is to take the user input in as a string, while forcing numeric input between 14 and 16 characters long. I think my code should do that, but I get a segmentation fault for numeric inputs with less than 14 or more than 16 characters, or any letters, instead of being reprompted. What's wrong with my code?

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void)
// declare variables
string cardnum = 0;

// Get value from user
    printf("Card Number:");
    cardnum = GetString();
while ((strlen(cardnum) < 14 || strlen(cardnum) > 16) && isdigit(cardnum) );

Classic error. The function isdigit() takes a single character as input. You are attempting to feed it an entire string, so it chokes, causing a seg fault. If you want to verify that every character in the string is a digit, you need to loop through it and test each character, one at a time.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • Makes sense. I'll work on that. Have I initialized the string correctly? – Avishai Fuss Jan 10 '16 at 21:56
  • no. You assigned an int to a string. Aside from that, it also sets the length of the string, which will cause problems later because it will likely be too short. You should set the length as you would an array here, assuming you know what it's maximum length will be. – Cliff B Jan 10 '16 at 22:20

You must log in to answer this question.

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