-1

I don't know why this basic code doesn't work well: it's printing just the first variable but not the second: b=a y=b

#include <stdio.h>

int main() {
    int b, y;
    b = getchar();
    putchar(b);
    y = getchar();
    putchar(y);
    return 0;
}
The output is:
/tmp/urA18H7eDx.o
a
a
b
dash: 2: b: not found
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Adam z
  • 1
  • 4
    Your second `getchar()` reads a newline. – Shawn Jul 23 '23 at 09:27
  • https://stackoverflow.com/questions/12544068/clarification-needed-regarding-getchar-and-newline You need additional `getchar()` call to consume a newline – Cythonista Jul 23 '23 at 09:28
  • 1
    The first character read is `a`, and the second character read is `\n`. Both characters are read after the newline is entered. The program outputs the two characters and exits. The `b` went straight to the shell (`dash`), as you can see by the error message. – Tom Karzes Jul 23 '23 at 09:34

1 Answers1

1

Here is what is happening when you execute the posted program:

  • b = getchar(); requests input from standard input.
  • no input is pending in the input stream buffer so input is requested from the terminal.
  • you type a and hit the Enter key.
  • the terminal is line buffered so the Enter key produces a newline character in the input stream and control is returned to the program after echoing the a and the newline to the terminal (first a in the posted execution trace).
  • getchar() returns the first byte available from the input stream buffer, namely the a character.
  • putchar(b); outputs the a to standard output. Standard output is line buffered to the terminal so the character is just stored in the output buffer until a newline is output.
  • y = getchar(); reads the next byte from standard input, which is the newline produced by the Enter key typed for the previous input.
  • putchar(y); outputs the newline to standard output. The output line is flushed, producing the a and a newline (second a in the posted execution trace).
  • if you then type b and hit the Enter key, the shell will read this line as a command and try and execute the b program, which cannot be found, producing the error message dash: 2: b: not found

You might be using some sort of IDE terminal window, if you were testing your program in a shell window, you would see the shell prompt after the second a output line.

chqrlie
  • 131,814
  • 10
  • 121
  • 189