I was going through some basic C codes and then I found a program intended to count numbers from a given input:
#include <stdio.h>
// count characters given as input
int main()
{
double nc;
for(nc = 0; getchar() != EOF; nc)
;
printf("%.0f\n", nc);
}
But as I ran the program on terminal (I'm using Debian 11), I'm getting no output for whatever I give as input. But pressing Ctrl C is terminating the program as it should.
CodePudding user response:
I had to modify you code a little bit to make it work
#include <stdio.h>
#include <signal.h>
static volatile int keepRunning = 1;
void intHandler(int dummy) {
keepRunning = 0;
}
// count characters given as input
int main()
{
int nc = -1;
signal(SIGINT, intHandler);
while (keepRunning) {
nc = 0;
for(nc = 0; getchar() != EOF; nc)
;
}
if(nc != -1)
printf("%i", nc);
}
pressing ctrl c will terminate the program before printing nc, so we have to catch the user pressing CTRL C, sing signal library
see this: Catch Ctrl-C in C
CodePudding user response:
I am using Win10, MS compiler, it worked fine...
C:\Users\Ahmed\Desktop>cl test.c
Microsoft (R) C/C Optimizing Compiler Version 17.00.50727.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
test.c
Microsoft (R) Incremental Linker Version 11.00.50727.1
Copyright (C) Microsoft Corporation. All rights reserved.
/out:test.exe
test.obj
C:\Users\Ahmed\Desktop>test.exe
adkjlad
asldkjasd
18
C:\Users\Ahmed\Desktop>
