So basically, I have this simple Hello World program and when executed, it outputs correctly.
#include <stdio.h>
int main(){
printf("Hello");
}
Output: Hello
But for some reason adding a scanf command will cause the program to not output anything. It will display that it's running but it won't display anything.
#include <stdio.h>
int num1;
int main(){
printf("Enter number: \n");
scanf("%d", &num1);
printf("%d", num1);
}
Output:
[Running] cd "d:\programming\" && gcc main.c -o main && "d:\programming\"main
I know my code is okay since I tried it on other IDEs and it worked correctly. I even copied code from the internet and tried to run in VSCode but it still didn't work. It still works perfectly fine yesterday but this problem just pops in nowhere.
I use Visual Studio Code 1.62.3 with C/C++, C/C++ Compile Run, and Code Runner extensions.
It's a buffering problem. When standard output (stdout, where printf writes) is connected to an actual terminal then it's line-buffered, which means output is actually written to the terminal when there's a newline.
However, VSCode probably uses its own terminal emulation and uses pipes to connect stdout to that terminal. That means the output will be fully buffered, and you need to explicitly flush it.
So modify the code as such:
printf("Enter number: \n");
fflush(stdout); // Actually write the output to standard output
scanf("%d", &num1);
printf("%d", num1);
That it works for the first example is because then the process terminates, and all output is flushed automatically.
Related
I want to insert the input given to a program into its output, in the moment it is read.
For instance, given the program:
#include <stdio.h>
int main() {
double x, y;
printf("Soma de dois números:\n");
printf("Digite o primeiro número: ");
scanf("%lf", &x);
printf("Digite o segundo número: ");
scanf("%lf", &y);
double soma = x + y;
printf("%lf + %lf = %lf\n", x, y, soma);
return 0;
}
when it is run with input redirection, I want the input inserted into the output, like the following:
$ echo -e "10\n25\n" | ./a.out
sum of two numbers
first number: 12
second number: 25
12.000000 + 25.000000 = 37.000000
Is there any library or tool to help me with that?
Edited Context: I intend to use this for correcting program exercises in a programming course. I want to see/show the program input and output as if it were run in an interactive console with the input being typed interactively, although the input is redirect from a text file.
As I noted in a comment:
There isn't an easy way to do that. The problem is that when you type at the terminal, the terminal driver echoes the characters typed. When you have I/O redirection (from a pipe or a file), the terminal driver is not involved, and neither the disk driver nor the pipe driver echoes to standard output.
One option might be to use a pseudo-terminal for the input to your program — but I've not tried it so that might not work. It's also fairly fiddly to set up (though there might well be a utility available on Linux, in particular, to do the job).
Or you could test to see whether the input is a terminal, doing nothing special if it is a terminal, and echoing the result of the input if it is. POSIX function isatty() determines whether the given file descriptor is a terminal or not.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
printf("Enter a number: ");
double d;
if (scanf("%lf", &d) != 1)
{
fprintf(stderr, "Failed to read a number!\n");
exit(EXIT_FAILURE);
}
if (!isatty(STDIN_FILENO))
printf("%lf\n", d);
printf("You entered: %lf\n", d);
return 0;
}
With that saved as source file tty47.c, I can run:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes -fno-common tty47.c -o tty47
$ tty47
Enter a number: 2.718282
You entered: 2.718282
$ echo "3.141593" | tty47
Enter a number: 3.141593
You entered: 3.141593
$ tty47 <<<'1.618034'
Enter a number: 1.618034
You entered: 1.618034
$
The first run accepts the input I type at the terminal, and that is echoed by the terminal driver. The other two runs know that the input comes from a pipe and a file respectively, and they echo the input. Note that the echo is not guaranteed to be exactly what the user entered — I cheated by typing numbers with 6 decimal places. Use fewer places and you get trailing zeros; use more and the result is rounded. You'll have to decide whether that matters.
An alternative strategy would read the input using getchar() or equivalent and echo each character with putchar() or equivalent if the input is not a terminal, and then use sscanf() to parse the data. That's definitely fiddlier.
I'm using linux manjaro. I have the following code (cons.c)
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *f=freopen("/dev/null", "a", stdout); //redirect stdout to /dev/null
FILE *g=freopen ("/dev/tty", "a", stdout); // redirect stdout back to console
printf("%p %p\n",f,g);
return 1;
}
I executed the following and got the expected result
[tom#sp4 src]$ gcc -g cons.c -o cons
[tom#sp4 src]$ ./cons
0x7f19897b7520 0x7f19897b7520
When I set a breakpoint on the bottom line and debug with the VS Code interactive debuggers however g returns null and the printf does nothing.
The problem lies with the interactive debuggers in VS Code. It works fine when debugging using gdb in a VS Code terminal. When using the interactive debuggers in VS code the second reopen returns null. Thanks to John Bollinger.
This is my program code:
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
void function() {
srand(time(NULL));
while(1) {
int n = rand();
printf("%d ", n);
//sleep(1);
}
}
int main() {
pid_t pid;
pid = fork();
if (pid == 0) {
function();
}
}
With the sleep line commented out (as in the code above) the program works fine (i.e. it prints a bunch of random numbers too fast to even see if they are actually random), but if I remove the comment the program doesn't print anything and exits (not even the first time, before it gets to the sleep), even though it compiles without warnings or errors with or without the comment.
but if I remove the comment the program doesn't print anything and exits
It does not print, but it does not really exit either. It will still be running a process in the background. And that process runs your infinite while loop.
Using your code in p.c:
$ gcc p.c
$ ./a.out
$ ps -A | grep a.out
267282 pts/0 00:00:00 a.out
$ killall a.out
$ killall a.out
a.out: no process found
The problem is that printf does not really print. It only sends data to the output buffer. In order to force the output buffer to be printed, invoke fflush(stdout)
If you're not flushing, then you just rely on the behavior of the terminal you're using. It's very common for terminals to flush when you write a newline character to the output stream. That's one reason why it's preferable to use printf("data\n") instead of printf("\ndata"). See this question for more info: https://softwareengineering.stackexchange.com/q/381711/283695
I'd suspect that if you just leave your program running, it will eventually print. It makes sense that it has a finite buffer and that it flushes when it gets full. But that's just an (educated) guess, and it depends on your terminal.
it prints a bunch of random numbers too fast to even see if they are actually random
How do you see if a sequence of numbers is random? (Playing the devils advocate)
I believe you need to call fflush(3) from time to time. See also setvbuf(3) and stdio(3) and sysconf(3).
I guess that if you coded:
while(1) {
int n = rand();
printf("%d ", n);
if (n % 4 == 0)
fflush(NULL);
sleep(1);
}
The behavior of your program might be more user friendly. The buffer of stdout might have several dozens of kilobytes at least.
BTW, I could be wrong. Check by reading a recent C draft standard (perhaps n2176).
At the very least, see this C reference website then syscalls(2), fork(2) and sleep(3).
You need to call waitpid(2) or a similar function for every successful fork(2).
If on Linux, read also Advanced Linux Programming and use both strace(1) and gdb(1) to understand the behavior of your program. With GCC don't forget to compile it as gcc -Wall -Wextra -g to get all warnings and debug info.
Consider also using the Clang static analyzer.
I ran a 4 line code and it compiled and linked without a hitch, but it refuses to print anything
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char* a = "book";
printf("%s\n", a);
return 0;
}
After compiling it and running the executable, nothing happens.
No error in the code.
Just write getch(); or getchar() before return 0;
to holding the output screen.
getch() or getchar() will hold the ouput screen for getting the user's input.
Works fine for me.
You've tagged this with terminal; if you are running it from the terminal, you should see some output, in my experience.
If you are running from an IDE,
keep the window open using Kapil K.'s answer;
keep the window open using an IDE setting, if there is one; or
find out where your IDE is putting the executable file, and run that from a terminal.
I have installed MinGW on netbeans for C and C++ programming.
Here is a simple code that I am trying to run on netbeans :
#include <stdio.h>
int main(int argc, char** argv) {
printf("Inside Main...\n");
int n;
printf("Enter : ");
scanf("%d", &n); // When I remove this line, it is working.
printf("You have entered %d.", n);
return (1);
}
Whenever I try to access any value from netbeans console, I don't see anything.
Output with scanf(...)
Output without scanf(...)
And if I try to run these code from cmd, all are working
for scanf() you must use Netbeans External Terminal !
Normal Run
You can also use Netbeans Standard Output !
But this is more misleading.
While you see an empty Terminal do input 123
after hit enter , you get the output all at once .
I had the same issue while running a CPP program.External output didn't helped me. I set the console type to Standard output and it solved the issue.
Right Click cpp Application-->properties-->run--->Consoletype to standard output