0
#include<stdio.h>
int main()
{
    char c;
    c=getchar();
    while(c!='\0')
    {
        printf("%c",c);
        c=getchar();
    }   
    return 0; 
}

We would like to terminate the program by entering NULL character from keyboard but it's not working.

Ganesh
  • 27
  • 3
  • You might find this useful: https://stackoverflow.com/questions/9124786/how-to-simulate-nul-character-from-keyboard#9124872 – psq Jul 07 '19 at 07:14
  • 1
    Note that the usual way to write this code is to read until the end-of-input, not some arbitrary character is reached. To do that you have to fix the type of `c` (it needs to be `int c;`) and change the loop condition: `while (c != EOF)` – melpomene Jul 07 '19 at 07:16
  • Do you want that if someone enter without writing anything then it should terminate or anything else? – GameChanger Jul 07 '19 at 07:18
  • @GameChanger yes correct, we are looking for the same. how can we terminate in this case.? – Ganesh Jul 07 '19 at 07:22
  • That's not a null character, that's a newline. – Barmar Jul 07 '19 at 07:25
  • If the user hits enter, that produces a `'\n'` character, not `'\0'`. – melpomene Jul 07 '19 at 07:25
  • just wanted to understand, is there any way where we can enter null character proactively in c language ? – Ganesh Jul 07 '19 at 07:28
  • Argh! Why do you keep changing your question? The linked duplicate explained exactly that: A way to enter the NUL character (regardless of language; it has nothing to do with C). – melpomene Jul 07 '19 at 07:30
  • @melpomene that way doesn't work for me – GameChanger Jul 07 '19 at 07:31
  • @GameChanger What terminal are you using? E.g. I can't find a way that works on the Windows 7 console, but there are no issues on Linux. – melpomene Jul 07 '19 at 07:32
  • I am using windows 10, and I also can't find a way that can help me to enter null character. – GameChanger Jul 07 '19 at 07:34
  • Don't enter a *nul-character* as the sentinel for end of string. Normal people don't write `string + nul-char` as input. Most enter `string` and expect the program to take that as input. That why `int c = getchar(); while (c != '\n' && c != EOF) c = getchar();` is the norm for *character-oriented* input. For *line-oriented* input, `fgets()` (or POSIX `getline`) are the norm. For *formatted-input*, then `fgets()` followed by `sscanf()` (or in some cases, simply `fscanf()` is warranted). Choose the correct tool for the job. – David C. Rankin Jul 07 '19 at 08:30

1 Answers1

2

As commented before, entering the '\0' character from terminal can be done by:

  • Ctrl+@

  • Ctrl+SPACE

The associated c code may be as follows:

#include <stdio.h>

int main()
{
  char c;

  do
  {
    c = getchar();
    if ((c == EOF) || (c == '\0'))
    {
      break;
    }
    printf("%c", c);
  } while (c != '\n');

  return 0;
}
Picaud Vincent
  • 10,518
  • 5
  • 31
  • 70