Home > Enterprise >  Detecting a new line character in C
Detecting a new line character in C

Time:09-27

I am trying to detect when a character in my scanf input is a new line char ('\n').

Apparently, when a user presses return/enter, a newline character is added to the variable. But I cannot detect it in my code.

I need some help, any input appreciated.

_Bool read_sequence(char s[])
{
  int i = 0;
  char userInput[20]; // char array
  int seq_len;
  seq_len = 20;

  printf("Enter a sequence of length %d: \n", seq_len);
  scanf("%s", &userInput); // user inputs their sequence

  // Loop until new line
  // looping through the user input in order to check that all bases are valid
  for (;;)
  {
    if (userInput[i] == '\n')
    {
      printf("yay!"); // -----NOT WORKING!-----
    }
    printf("ASCII value of %c = %d\n", userInput[i], userInput[i]);
    i  ;
  }

CodePudding user response:

_Bool read_sequence(char *s, size_t len)
{
    printf("Enter a sequence of length %d: \n", len);
    fgets(s, len - 1, stdin); // user inputs their sequence

    while(*s)
    {
        printf("ASCII value of `%c` = %d\n", (*s > 31 && *s < 127) ? *s : ' ', *s);
        if (*s   == '\n') return true;
    }
    return false;
}
int main(void)
{
    char s[20];

    printf("Entered string %s\n", read_sequence(s, 20) ? "contains `\\n`" : "does not contain `\\n");
}

https://godbolt.org/z/TzqEf73vG

CodePudding user response:

scanf() doesn't read the \n entered by the user. It stops reading when it finds a whitespace, a newline, or a tab. Moreover, it's a dangerous function to use and you should defenitely avoid using it. Instead, use fgets(). It reads an entire line including whitespaces and tabs, and stops reading when it reads a newline.

Here is how you can do it:

int main(void)
{
    char userInput[20]; // char array

    printf("Enter a sequence of length %d: \n", sizeof userInput - 1);
    
    if (!fgets(userInput, sizeof userInput, stdin)) { // check for input errors
        printf("Input error\n");
        return 1;
    }

    // Loop until new line
    // looping through the user input in order to check that all bases are valid
    int i;
    for (i = 0; i < sizeof userInput; i  ) {
        if (userInput[i] == '\n')
            printf("yay!");

        printf("ASCII value of %c = %d\n", userInput[i], userInput[i]);
    }
}
  •  Tags:  
  • c
  • Related