Search code examples
cio

Character compared to a digit


I am very new to programming, specifically C. I was trying to do a hide/mask a password as an excercise. Made this code to but I was not able to input a \n character.

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


int main(){
   char pasword[10], ch;
   int i;

   while(i<=9 )
   {
      ch=getch();
      if((ch >= 'a' && ch<='z') || (ch>='A' && ch<='Z'))
      {
        pasword[i] = ch;
        i++;
        printf("*");
      }
   }

   pasword[i] = '\0';

   printf("Password: %s", pasword);
   return 0;
   }

So I tried to search around different forums, found a snippet of code and added it to my if statement.

/* some code at the top */
}else if(ch == 13){
    break;
}

It somehow made me allow to input a \n or 'Enter'.

Why is ch compared to 13? Or what is 13 in this sense? Why is it that when I change 13 to another number I couldn't press Enter?

May I also add that why couldn't I erase the text I have typed?


Solution

  • First, this code is with its own faults to be dealt with.

    You need to initialize i to a valid value, mostly the 0. Then your while loop would be guaranteed to get executed.

    while(i <= 9)
    

    Additionally, since your are adding a '\0' in the last-used index, your loop should execute at the most 9 times. So, while(i <= 9) should be changed to while(i < 9) so that it gets executed 9 times instead of 10.

    Now, to answer your real question, 13 (0x0D in Hexadecimal) is called Carriage Return. Refer any (correct) ASCII table such as this one here.

    The wikipedia says,

    A carriage return, sometimes known as a cartridge return and often shortened to CR, or return, is a control character or mechanism used to reset a device's position to the beginning of a line of text. It is closely associated with the line feed and newline concepts, although it can be considered separately in its own right.

    With further reference from the same,

    In computing, the carriage return is one of the control characters in ASCII code, Unicode, EBCDIC, and many other codes. It commands a printer, or other output system such as the display of a system console, to move the position of the cursor to the first position on the same line. It was mostly used along with line feed (LF), a move to the next line, so that together they start a new line. Together, this sequence can be referred to as CRLF.

    And,

    Many computer programs use the carriage return character, alone or with a line feed, to signal the end of a line of text.

    Reading at the last cited text, you could possibly imagine why any of user input programs proceed from scanf after user presses an ENTER key. Thats the usual case when it is treated as a 'End of line'.

    So when,

    if((ch >= 'a' && ch<='z') || (ch>='A' && ch<='Z'))
    {
    
    }
    else if(ch == 13) //This has allowed you to check if the user has pressed Enter on keyboard.
    {
        break;
    }