Search code examples
cstringstrcmpgetchar

c read string is causing a crash


 int iPassCode, iNumber = 0;

void main()
{
    iNumber = get_name();
    iPassCode = get_code();
    name_strucutre();
}

int get_name()
{
    printf("Please enter your name: ");
    cName[MAX_NAME_LEN] = getchar();
    if(strcmp(cName,"leia"||"Leia"))
    {
        iNumber = 1;
    }
    if(strcmp(cName,"darth"||"Darth"))
    {
        iNumber = 2;
    }
    if(strcmp(cName,"r2d2"||"R2D2"))
    {
        iNumber = 3;
    }
    if(strcmp(cName,"solo"||"Solo"))
    {
        iNumber = 4;
    }
    if(strcmp(cName,"jabba"||"Jabba"))
    {
        iNumber = 5;
    }
    if(strcmp(cName,"yoda"||"Yoda"))
    {
        iNumber = 6;
    }
    else
    {
        iNumber = 0;
    }
    return(iNumber);
}

int get_code()
{
    printf("Please enter your pass code: ");
    scanf("%d", iPassCode);
    return (iPassCode);
}

I got a couple of my functions here. One of them I think its the get name() function is causing the program to crash. Right now all I'm trying to do is gather the name and the pass code from the user and pass the info back to main(). I don't want to pass the whole name back though just a singular number.


Solution

  • There are multiple issues, let us analyze them one by one

    1. First of all,

      cName[MAX_NAME_LEN] = getchar();
      

      is invalid because

      • As per the latest standard, default to int is no longer a standard. You need to have the data type defined

      • A single call to getchar() reads one char. You need a loop, at least.

      You need to change to something like

      char cName[MAX_NAME_LEN] = {0};
      

      and then, loop over getchar() to read the input.

      Otherwise, for better, use fgets() to read and store the input.

    2. That said, you cannot compare multiple strings in a single call like

      if(strcmp(cName,"leia"||"Leia"))
      

      this is essentially

      if(strcmp(cName,1))
      

      which is again illegal. You can make use strcasecmp() to ignore the case. Otherwise, to be strictly standard-conforming, you have to use separate strcmp() calls to compare the string with each validator.

      and yes, strcmp() returns 0 on success (match).

    3. You are writing

      scanf("%d", iPassCode);
      

      which should be

      scanf("%d", &iPassCode);  //missed the address-of
      

    After all these, from a coding style point of view, let me add that, return is a keyword, don't make it look like a function call.