How do you write a C program to increment a number by keypress and auto-decrement it per second?
Clash Royale CLAN TAG#URR8PPP
up vote
7
down vote
favorite
I'm trying to write a program in which a number starts from 0, but when you press any key, it gets incremented by 1. If nothing is pressed, it keeps on decreasing by 1 per second until it reaches 0. Every increment or decrement is displayed in the console window.
Problem with my approach is that nothing happens until I press a key (that is, it checks if anything is pressed with getch()
). How do I check, if nothing is pressed? And of course, !getch()
doesn't work because for that to work, it'll still need to check for keypress which nullifies the purpose itself.
OS: Windows 10 Enterprise
IDE: Code::Blocks
void main()
int i, counter = 0;
for (i = 0; i < 1000; i++)
delay(1000);
// if a key is pressed, increment it
if (getch())
counter += 1;
printf("n%d", counter);
while (counter >= 1)
if (getch())
break;
else
delay(1000);
counter--;
printf("n%d", counter);
c windows user-input
New contributor
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
 |Â
show 3 more comments
up vote
7
down vote
favorite
I'm trying to write a program in which a number starts from 0, but when you press any key, it gets incremented by 1. If nothing is pressed, it keeps on decreasing by 1 per second until it reaches 0. Every increment or decrement is displayed in the console window.
Problem with my approach is that nothing happens until I press a key (that is, it checks if anything is pressed with getch()
). How do I check, if nothing is pressed? And of course, !getch()
doesn't work because for that to work, it'll still need to check for keypress which nullifies the purpose itself.
OS: Windows 10 Enterprise
IDE: Code::Blocks
void main()
int i, counter = 0;
for (i = 0; i < 1000; i++)
delay(1000);
// if a key is pressed, increment it
if (getch())
counter += 1;
printf("n%d", counter);
while (counter >= 1)
if (getch())
break;
else
delay(1000);
counter--;
printf("n%d", counter);
c windows user-input
New contributor
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Do not use delays
– P__J__
2 hours ago
Why not? If there's some adverse effect I don't know about, what alternative can I use to simulate a delay? Nested for loops are highly CPU consuming so I avoided that. I do not want the decrement to happen immediately because that woudn't give the user enough time to increment it in the first place.
– Ritika
2 hours ago
If you want to do multiple things at once (waiting for delay to finish and waiting for a keystroke), you might want to look into multithreading
– MemAllox
2 hours ago
If you know better do not ask
– P__J__
1 hour ago
2
Since you are callinggetch()
, and talk about the "console window", my guess is that you are programming on Windows? Is that correct? You need to state which environment you are using, since things like these are done differently in different operating systems, and it looks like some of the answers assume Linux instead of Windows.
– Thomas Padron-McCarthy
1 hour ago
 |Â
show 3 more comments
up vote
7
down vote
favorite
up vote
7
down vote
favorite
I'm trying to write a program in which a number starts from 0, but when you press any key, it gets incremented by 1. If nothing is pressed, it keeps on decreasing by 1 per second until it reaches 0. Every increment or decrement is displayed in the console window.
Problem with my approach is that nothing happens until I press a key (that is, it checks if anything is pressed with getch()
). How do I check, if nothing is pressed? And of course, !getch()
doesn't work because for that to work, it'll still need to check for keypress which nullifies the purpose itself.
OS: Windows 10 Enterprise
IDE: Code::Blocks
void main()
int i, counter = 0;
for (i = 0; i < 1000; i++)
delay(1000);
// if a key is pressed, increment it
if (getch())
counter += 1;
printf("n%d", counter);
while (counter >= 1)
if (getch())
break;
else
delay(1000);
counter--;
printf("n%d", counter);
c windows user-input
New contributor
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
I'm trying to write a program in which a number starts from 0, but when you press any key, it gets incremented by 1. If nothing is pressed, it keeps on decreasing by 1 per second until it reaches 0. Every increment or decrement is displayed in the console window.
Problem with my approach is that nothing happens until I press a key (that is, it checks if anything is pressed with getch()
). How do I check, if nothing is pressed? And of course, !getch()
doesn't work because for that to work, it'll still need to check for keypress which nullifies the purpose itself.
OS: Windows 10 Enterprise
IDE: Code::Blocks
void main()
int i, counter = 0;
for (i = 0; i < 1000; i++)
delay(1000);
// if a key is pressed, increment it
if (getch())
counter += 1;
printf("n%d", counter);
while (counter >= 1)
if (getch())
break;
else
delay(1000);
counter--;
printf("n%d", counter);
c windows user-input
c windows user-input
New contributor
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 1 min ago
New contributor
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 2 hours ago
Ritika
392
392
New contributor
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Ritika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Do not use delays
– P__J__
2 hours ago
Why not? If there's some adverse effect I don't know about, what alternative can I use to simulate a delay? Nested for loops are highly CPU consuming so I avoided that. I do not want the decrement to happen immediately because that woudn't give the user enough time to increment it in the first place.
– Ritika
2 hours ago
If you want to do multiple things at once (waiting for delay to finish and waiting for a keystroke), you might want to look into multithreading
– MemAllox
2 hours ago
If you know better do not ask
– P__J__
1 hour ago
2
Since you are callinggetch()
, and talk about the "console window", my guess is that you are programming on Windows? Is that correct? You need to state which environment you are using, since things like these are done differently in different operating systems, and it looks like some of the answers assume Linux instead of Windows.
– Thomas Padron-McCarthy
1 hour ago
 |Â
show 3 more comments
Do not use delays
– P__J__
2 hours ago
Why not? If there's some adverse effect I don't know about, what alternative can I use to simulate a delay? Nested for loops are highly CPU consuming so I avoided that. I do not want the decrement to happen immediately because that woudn't give the user enough time to increment it in the first place.
– Ritika
2 hours ago
If you want to do multiple things at once (waiting for delay to finish and waiting for a keystroke), you might want to look into multithreading
– MemAllox
2 hours ago
If you know better do not ask
– P__J__
1 hour ago
2
Since you are callinggetch()
, and talk about the "console window", my guess is that you are programming on Windows? Is that correct? You need to state which environment you are using, since things like these are done differently in different operating systems, and it looks like some of the answers assume Linux instead of Windows.
– Thomas Padron-McCarthy
1 hour ago
Do not use delays
– P__J__
2 hours ago
Do not use delays
– P__J__
2 hours ago
Why not? If there's some adverse effect I don't know about, what alternative can I use to simulate a delay? Nested for loops are highly CPU consuming so I avoided that. I do not want the decrement to happen immediately because that woudn't give the user enough time to increment it in the first place.
– Ritika
2 hours ago
Why not? If there's some adverse effect I don't know about, what alternative can I use to simulate a delay? Nested for loops are highly CPU consuming so I avoided that. I do not want the decrement to happen immediately because that woudn't give the user enough time to increment it in the first place.
– Ritika
2 hours ago
If you want to do multiple things at once (waiting for delay to finish and waiting for a keystroke), you might want to look into multithreading
– MemAllox
2 hours ago
If you want to do multiple things at once (waiting for delay to finish and waiting for a keystroke), you might want to look into multithreading
– MemAllox
2 hours ago
If you know better do not ask
– P__J__
1 hour ago
If you know better do not ask
– P__J__
1 hour ago
2
2
Since you are calling
getch()
, and talk about the "console window", my guess is that you are programming on Windows? Is that correct? You need to state which environment you are using, since things like these are done differently in different operating systems, and it looks like some of the answers assume Linux instead of Windows.– Thomas Padron-McCarthy
1 hour ago
Since you are calling
getch()
, and talk about the "console window", my guess is that you are programming on Windows? Is that correct? You need to state which environment you are using, since things like these are done differently in different operating systems, and it looks like some of the answers assume Linux instead of Windows.– Thomas Padron-McCarthy
1 hour ago
 |Â
show 3 more comments
5 Answers
5
active
oldest
votes
up vote
5
down vote
Welcome to the site. The following short program requires neither ncurses or threads. It does, however, require changing the terminal attributes - using tcsetattr()
. This will work on Linux and Unix-like systems, but not on Windows - which does not include the termios.h
header file. (Perhaps see this post if you are interested in that subject.)
#include <stdio.h>
#include <string.h>
#include <termios.h>
int main(int argc, char *argv) ECHO);
new_attr.c_cc[VMIN] = 0;
// Wait up to 10 deciseconds (i.e. 1 second)
new_attr.c_cc[VTIME] = 10;
tcsetattr(fileno(stdin), TCSANOW, &new_attr);
printf("Starting with n = %dn", n);
do
c = getchar();
if (c != EOF)
n++;
printf("Key pressed!n", n);
printf("n++ => %dn", n);
else
n--;
printf("n-- => %dn", n);
if (n == 0)
printf("Exiting ...n");
break;
while (c != 'q');
tcsetattr(fileno(stdin), TCSANOW, &orig_attr);
return 0;
The vital points are that
new_attr.c_lflag &= ~(ICANON | ECHO);
takes the terminal out of canonical mode (and disables character 'echo'),
new_attr.c_cc[VMIN] = 0;
places it in polling (rather than 'blocking') mode, and
new_attr.c_cc[VTIME] = 10;
instructs the program to wait up till 10 deciseconds for input.
int c
to be able to safely compare withEOF
:)
– pmg
17 mins ago
add a comment |Â
up vote
1
down vote
Here is a pthread example that works on linux. The concept is ok, but there are probably existing loops/libraries for this.
#include <stdio.h>
#include<pthread.h>
void *timer(void* arg)
int* counter = (int*)arg;
while(*counter > 0)
int a = *counter;
printf("counter: %d n", a);
*counter = a - 1;
sleep(1);
int main(int arg_c, char** args)
int i = 100;
pthread_t loop;
pthread_create(&loop, NULL, timer, &i);
while(i>0)
i++;
getchar();
printf("inc counter: %d n", i);
printf("%d aftern", i);
pthread_join(loop, NULL);
return 0;
This starts a second thread, which has the countdown on it. That decrements the counter every second. On the main thread it has a loop with getchar. They both modify i
.
add a comment |Â
up vote
1
down vote
This could be done with multithreading as already suggested, but there are other possibilities.
ncurses for example has the possibility to wait for input and with a timeout.
An example for ncurses (written by Constantin):
initscr();
timeout(1000);
char c = getch();
endwin();
printf("Char: %cn", c);
It is also possible to check whether input is available with if (!feof(stdin))
and only fetch the input if available.
I think poll
could also be used on stdin
to check if input is available.
And to make your program more responsive you could lower your sleep or delay to for example 100ms and only decrement if ten iterations of sleep have passed without input. This will reduce the input lag.
add a comment |Â
up vote
1
down vote
You need use thread, and need use __sync_add_and_fetch and __sync_sub_and_fetch to avoid concurrency problem
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
static void* thread(void* p)
int* counter = (int*)p;
while (1)
if (*counter > 0)
__sync_sub_and_fetch(counter, 1);
printf("n%d", *counter);
else
sleep(1);
return NULL;
int main()
int counter = 0;
pthread_t pid;
if (pthread_create(&pid, NULL, thread, &counter))
fprintf(stderr, "Create thread failed");
exit(1);
while(1)
getchar();
__sync_add_and_fetch(&counter, 1);
printf("n%d", counter);
return 0;
New contributor
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
up vote
1
down vote
Another example using ncurses and POSIX timers and signals (and global variables).
#include <ncurses.h>
#include <signal.h>
#include <time.h>
int changed, value;
void timer(union sigval t)
(void)t; // suppress unused warning
changed = 1;
value--;
int main(void)
int ch;
timer_t tid;
struct itimerspec its = 0;
struct sigevent se = 0;
se.sigev_notify = SIGEV_THREAD;
se.sigev_notify_function = timer;
its.it_value.tv_sec = its.it_interval.tv_sec = 1;
timer_create(CLOCK_REALTIME, &se, &tid);
timer_settime(tid, 0, &its, NULL);
initscr(); raw(); noecho(); nodelay(stdscr, TRUE);
for (;;)
ch = getch();
if (ch != ERR)
if (ch == 'q') break;
changed = 1;
value++;
if (changed)
changed = 0;
move(0, 0);
printw("%d ", value);
move(0, 0);
refresh();
endwin();
add a comment |Â
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
5
down vote
Welcome to the site. The following short program requires neither ncurses or threads. It does, however, require changing the terminal attributes - using tcsetattr()
. This will work on Linux and Unix-like systems, but not on Windows - which does not include the termios.h
header file. (Perhaps see this post if you are interested in that subject.)
#include <stdio.h>
#include <string.h>
#include <termios.h>
int main(int argc, char *argv) ECHO);
new_attr.c_cc[VMIN] = 0;
// Wait up to 10 deciseconds (i.e. 1 second)
new_attr.c_cc[VTIME] = 10;
tcsetattr(fileno(stdin), TCSANOW, &new_attr);
printf("Starting with n = %dn", n);
do
c = getchar();
if (c != EOF)
n++;
printf("Key pressed!n", n);
printf("n++ => %dn", n);
else
n--;
printf("n-- => %dn", n);
if (n == 0)
printf("Exiting ...n");
break;
while (c != 'q');
tcsetattr(fileno(stdin), TCSANOW, &orig_attr);
return 0;
The vital points are that
new_attr.c_lflag &= ~(ICANON | ECHO);
takes the terminal out of canonical mode (and disables character 'echo'),
new_attr.c_cc[VMIN] = 0;
places it in polling (rather than 'blocking') mode, and
new_attr.c_cc[VTIME] = 10;
instructs the program to wait up till 10 deciseconds for input.
int c
to be able to safely compare withEOF
:)
– pmg
17 mins ago
add a comment |Â
up vote
5
down vote
Welcome to the site. The following short program requires neither ncurses or threads. It does, however, require changing the terminal attributes - using tcsetattr()
. This will work on Linux and Unix-like systems, but not on Windows - which does not include the termios.h
header file. (Perhaps see this post if you are interested in that subject.)
#include <stdio.h>
#include <string.h>
#include <termios.h>
int main(int argc, char *argv) ECHO);
new_attr.c_cc[VMIN] = 0;
// Wait up to 10 deciseconds (i.e. 1 second)
new_attr.c_cc[VTIME] = 10;
tcsetattr(fileno(stdin), TCSANOW, &new_attr);
printf("Starting with n = %dn", n);
do
c = getchar();
if (c != EOF)
n++;
printf("Key pressed!n", n);
printf("n++ => %dn", n);
else
n--;
printf("n-- => %dn", n);
if (n == 0)
printf("Exiting ...n");
break;
while (c != 'q');
tcsetattr(fileno(stdin), TCSANOW, &orig_attr);
return 0;
The vital points are that
new_attr.c_lflag &= ~(ICANON | ECHO);
takes the terminal out of canonical mode (and disables character 'echo'),
new_attr.c_cc[VMIN] = 0;
places it in polling (rather than 'blocking') mode, and
new_attr.c_cc[VTIME] = 10;
instructs the program to wait up till 10 deciseconds for input.
int c
to be able to safely compare withEOF
:)
– pmg
17 mins ago
add a comment |Â
up vote
5
down vote
up vote
5
down vote
Welcome to the site. The following short program requires neither ncurses or threads. It does, however, require changing the terminal attributes - using tcsetattr()
. This will work on Linux and Unix-like systems, but not on Windows - which does not include the termios.h
header file. (Perhaps see this post if you are interested in that subject.)
#include <stdio.h>
#include <string.h>
#include <termios.h>
int main(int argc, char *argv) ECHO);
new_attr.c_cc[VMIN] = 0;
// Wait up to 10 deciseconds (i.e. 1 second)
new_attr.c_cc[VTIME] = 10;
tcsetattr(fileno(stdin), TCSANOW, &new_attr);
printf("Starting with n = %dn", n);
do
c = getchar();
if (c != EOF)
n++;
printf("Key pressed!n", n);
printf("n++ => %dn", n);
else
n--;
printf("n-- => %dn", n);
if (n == 0)
printf("Exiting ...n");
break;
while (c != 'q');
tcsetattr(fileno(stdin), TCSANOW, &orig_attr);
return 0;
The vital points are that
new_attr.c_lflag &= ~(ICANON | ECHO);
takes the terminal out of canonical mode (and disables character 'echo'),
new_attr.c_cc[VMIN] = 0;
places it in polling (rather than 'blocking') mode, and
new_attr.c_cc[VTIME] = 10;
instructs the program to wait up till 10 deciseconds for input.
Welcome to the site. The following short program requires neither ncurses or threads. It does, however, require changing the terminal attributes - using tcsetattr()
. This will work on Linux and Unix-like systems, but not on Windows - which does not include the termios.h
header file. (Perhaps see this post if you are interested in that subject.)
#include <stdio.h>
#include <string.h>
#include <termios.h>
int main(int argc, char *argv) ECHO);
new_attr.c_cc[VMIN] = 0;
// Wait up to 10 deciseconds (i.e. 1 second)
new_attr.c_cc[VTIME] = 10;
tcsetattr(fileno(stdin), TCSANOW, &new_attr);
printf("Starting with n = %dn", n);
do
c = getchar();
if (c != EOF)
n++;
printf("Key pressed!n", n);
printf("n++ => %dn", n);
else
n--;
printf("n-- => %dn", n);
if (n == 0)
printf("Exiting ...n");
break;
while (c != 'q');
tcsetattr(fileno(stdin), TCSANOW, &orig_attr);
return 0;
The vital points are that
new_attr.c_lflag &= ~(ICANON | ECHO);
takes the terminal out of canonical mode (and disables character 'echo'),
new_attr.c_cc[VMIN] = 0;
places it in polling (rather than 'blocking') mode, and
new_attr.c_cc[VTIME] = 10;
instructs the program to wait up till 10 deciseconds for input.
edited 1 hour ago
answered 1 hour ago
David Collins
95616
95616
int c
to be able to safely compare withEOF
:)
– pmg
17 mins ago
add a comment |Â
int c
to be able to safely compare withEOF
:)
– pmg
17 mins ago
int c
to be able to safely compare with EOF
:)– pmg
17 mins ago
int c
to be able to safely compare with EOF
:)– pmg
17 mins ago
add a comment |Â
up vote
1
down vote
Here is a pthread example that works on linux. The concept is ok, but there are probably existing loops/libraries for this.
#include <stdio.h>
#include<pthread.h>
void *timer(void* arg)
int* counter = (int*)arg;
while(*counter > 0)
int a = *counter;
printf("counter: %d n", a);
*counter = a - 1;
sleep(1);
int main(int arg_c, char** args)
int i = 100;
pthread_t loop;
pthread_create(&loop, NULL, timer, &i);
while(i>0)
i++;
getchar();
printf("inc counter: %d n", i);
printf("%d aftern", i);
pthread_join(loop, NULL);
return 0;
This starts a second thread, which has the countdown on it. That decrements the counter every second. On the main thread it has a loop with getchar. They both modify i
.
add a comment |Â
up vote
1
down vote
Here is a pthread example that works on linux. The concept is ok, but there are probably existing loops/libraries for this.
#include <stdio.h>
#include<pthread.h>
void *timer(void* arg)
int* counter = (int*)arg;
while(*counter > 0)
int a = *counter;
printf("counter: %d n", a);
*counter = a - 1;
sleep(1);
int main(int arg_c, char** args)
int i = 100;
pthread_t loop;
pthread_create(&loop, NULL, timer, &i);
while(i>0)
i++;
getchar();
printf("inc counter: %d n", i);
printf("%d aftern", i);
pthread_join(loop, NULL);
return 0;
This starts a second thread, which has the countdown on it. That decrements the counter every second. On the main thread it has a loop with getchar. They both modify i
.
add a comment |Â
up vote
1
down vote
up vote
1
down vote
Here is a pthread example that works on linux. The concept is ok, but there are probably existing loops/libraries for this.
#include <stdio.h>
#include<pthread.h>
void *timer(void* arg)
int* counter = (int*)arg;
while(*counter > 0)
int a = *counter;
printf("counter: %d n", a);
*counter = a - 1;
sleep(1);
int main(int arg_c, char** args)
int i = 100;
pthread_t loop;
pthread_create(&loop, NULL, timer, &i);
while(i>0)
i++;
getchar();
printf("inc counter: %d n", i);
printf("%d aftern", i);
pthread_join(loop, NULL);
return 0;
This starts a second thread, which has the countdown on it. That decrements the counter every second. On the main thread it has a loop with getchar. They both modify i
.
Here is a pthread example that works on linux. The concept is ok, but there are probably existing loops/libraries for this.
#include <stdio.h>
#include<pthread.h>
void *timer(void* arg)
int* counter = (int*)arg;
while(*counter > 0)
int a = *counter;
printf("counter: %d n", a);
*counter = a - 1;
sleep(1);
int main(int arg_c, char** args)
int i = 100;
pthread_t loop;
pthread_create(&loop, NULL, timer, &i);
while(i>0)
i++;
getchar();
printf("inc counter: %d n", i);
printf("%d aftern", i);
pthread_join(loop, NULL);
return 0;
This starts a second thread, which has the countdown on it. That decrements the counter every second. On the main thread it has a loop with getchar. They both modify i
.
answered 2 hours ago
matt
4,0501923
4,0501923
add a comment |Â
add a comment |Â
up vote
1
down vote
This could be done with multithreading as already suggested, but there are other possibilities.
ncurses for example has the possibility to wait for input and with a timeout.
An example for ncurses (written by Constantin):
initscr();
timeout(1000);
char c = getch();
endwin();
printf("Char: %cn", c);
It is also possible to check whether input is available with if (!feof(stdin))
and only fetch the input if available.
I think poll
could also be used on stdin
to check if input is available.
And to make your program more responsive you could lower your sleep or delay to for example 100ms and only decrement if ten iterations of sleep have passed without input. This will reduce the input lag.
add a comment |Â
up vote
1
down vote
This could be done with multithreading as already suggested, but there are other possibilities.
ncurses for example has the possibility to wait for input and with a timeout.
An example for ncurses (written by Constantin):
initscr();
timeout(1000);
char c = getch();
endwin();
printf("Char: %cn", c);
It is also possible to check whether input is available with if (!feof(stdin))
and only fetch the input if available.
I think poll
could also be used on stdin
to check if input is available.
And to make your program more responsive you could lower your sleep or delay to for example 100ms and only decrement if ten iterations of sleep have passed without input. This will reduce the input lag.
add a comment |Â
up vote
1
down vote
up vote
1
down vote
This could be done with multithreading as already suggested, but there are other possibilities.
ncurses for example has the possibility to wait for input and with a timeout.
An example for ncurses (written by Constantin):
initscr();
timeout(1000);
char c = getch();
endwin();
printf("Char: %cn", c);
It is also possible to check whether input is available with if (!feof(stdin))
and only fetch the input if available.
I think poll
could also be used on stdin
to check if input is available.
And to make your program more responsive you could lower your sleep or delay to for example 100ms and only decrement if ten iterations of sleep have passed without input. This will reduce the input lag.
This could be done with multithreading as already suggested, but there are other possibilities.
ncurses for example has the possibility to wait for input and with a timeout.
An example for ncurses (written by Constantin):
initscr();
timeout(1000);
char c = getch();
endwin();
printf("Char: %cn", c);
It is also possible to check whether input is available with if (!feof(stdin))
and only fetch the input if available.
I think poll
could also be used on stdin
to check if input is available.
And to make your program more responsive you could lower your sleep or delay to for example 100ms and only decrement if ten iterations of sleep have passed without input. This will reduce the input lag.
edited 1 hour ago
answered 2 hours ago


Kami Kaze
1,618621
1,618621
add a comment |Â
add a comment |Â
up vote
1
down vote
You need use thread, and need use __sync_add_and_fetch and __sync_sub_and_fetch to avoid concurrency problem
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
static void* thread(void* p)
int* counter = (int*)p;
while (1)
if (*counter > 0)
__sync_sub_and_fetch(counter, 1);
printf("n%d", *counter);
else
sleep(1);
return NULL;
int main()
int counter = 0;
pthread_t pid;
if (pthread_create(&pid, NULL, thread, &counter))
fprintf(stderr, "Create thread failed");
exit(1);
while(1)
getchar();
__sync_add_and_fetch(&counter, 1);
printf("n%d", counter);
return 0;
New contributor
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
up vote
1
down vote
You need use thread, and need use __sync_add_and_fetch and __sync_sub_and_fetch to avoid concurrency problem
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
static void* thread(void* p)
int* counter = (int*)p;
while (1)
if (*counter > 0)
__sync_sub_and_fetch(counter, 1);
printf("n%d", *counter);
else
sleep(1);
return NULL;
int main()
int counter = 0;
pthread_t pid;
if (pthread_create(&pid, NULL, thread, &counter))
fprintf(stderr, "Create thread failed");
exit(1);
while(1)
getchar();
__sync_add_and_fetch(&counter, 1);
printf("n%d", counter);
return 0;
New contributor
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
up vote
1
down vote
up vote
1
down vote
You need use thread, and need use __sync_add_and_fetch and __sync_sub_and_fetch to avoid concurrency problem
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
static void* thread(void* p)
int* counter = (int*)p;
while (1)
if (*counter > 0)
__sync_sub_and_fetch(counter, 1);
printf("n%d", *counter);
else
sleep(1);
return NULL;
int main()
int counter = 0;
pthread_t pid;
if (pthread_create(&pid, NULL, thread, &counter))
fprintf(stderr, "Create thread failed");
exit(1);
while(1)
getchar();
__sync_add_and_fetch(&counter, 1);
printf("n%d", counter);
return 0;
New contributor
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You need use thread, and need use __sync_add_and_fetch and __sync_sub_and_fetch to avoid concurrency problem
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
static void* thread(void* p)
int* counter = (int*)p;
while (1)
if (*counter > 0)
__sync_sub_and_fetch(counter, 1);
printf("n%d", *counter);
else
sleep(1);
return NULL;
int main()
int counter = 0;
pthread_t pid;
if (pthread_create(&pid, NULL, thread, &counter))
fprintf(stderr, "Create thread failed");
exit(1);
while(1)
getchar();
__sync_add_and_fetch(&counter, 1);
printf("n%d", counter);
return 0;
New contributor
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 1 hour ago
New contributor
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered 1 hour ago


sundb
913
913
New contributor
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
sundb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
add a comment |Â
up vote
1
down vote
Another example using ncurses and POSIX timers and signals (and global variables).
#include <ncurses.h>
#include <signal.h>
#include <time.h>
int changed, value;
void timer(union sigval t)
(void)t; // suppress unused warning
changed = 1;
value--;
int main(void)
int ch;
timer_t tid;
struct itimerspec its = 0;
struct sigevent se = 0;
se.sigev_notify = SIGEV_THREAD;
se.sigev_notify_function = timer;
its.it_value.tv_sec = its.it_interval.tv_sec = 1;
timer_create(CLOCK_REALTIME, &se, &tid);
timer_settime(tid, 0, &its, NULL);
initscr(); raw(); noecho(); nodelay(stdscr, TRUE);
for (;;)
ch = getch();
if (ch != ERR)
if (ch == 'q') break;
changed = 1;
value++;
if (changed)
changed = 0;
move(0, 0);
printw("%d ", value);
move(0, 0);
refresh();
endwin();
add a comment |Â
up vote
1
down vote
Another example using ncurses and POSIX timers and signals (and global variables).
#include <ncurses.h>
#include <signal.h>
#include <time.h>
int changed, value;
void timer(union sigval t)
(void)t; // suppress unused warning
changed = 1;
value--;
int main(void)
int ch;
timer_t tid;
struct itimerspec its = 0;
struct sigevent se = 0;
se.sigev_notify = SIGEV_THREAD;
se.sigev_notify_function = timer;
its.it_value.tv_sec = its.it_interval.tv_sec = 1;
timer_create(CLOCK_REALTIME, &se, &tid);
timer_settime(tid, 0, &its, NULL);
initscr(); raw(); noecho(); nodelay(stdscr, TRUE);
for (;;)
ch = getch();
if (ch != ERR)
if (ch == 'q') break;
changed = 1;
value++;
if (changed)
changed = 0;
move(0, 0);
printw("%d ", value);
move(0, 0);
refresh();
endwin();
add a comment |Â
up vote
1
down vote
up vote
1
down vote
Another example using ncurses and POSIX timers and signals (and global variables).
#include <ncurses.h>
#include <signal.h>
#include <time.h>
int changed, value;
void timer(union sigval t)
(void)t; // suppress unused warning
changed = 1;
value--;
int main(void)
int ch;
timer_t tid;
struct itimerspec its = 0;
struct sigevent se = 0;
se.sigev_notify = SIGEV_THREAD;
se.sigev_notify_function = timer;
its.it_value.tv_sec = its.it_interval.tv_sec = 1;
timer_create(CLOCK_REALTIME, &se, &tid);
timer_settime(tid, 0, &its, NULL);
initscr(); raw(); noecho(); nodelay(stdscr, TRUE);
for (;;)
ch = getch();
if (ch != ERR)
if (ch == 'q') break;
changed = 1;
value++;
if (changed)
changed = 0;
move(0, 0);
printw("%d ", value);
move(0, 0);
refresh();
endwin();
Another example using ncurses and POSIX timers and signals (and global variables).
#include <ncurses.h>
#include <signal.h>
#include <time.h>
int changed, value;
void timer(union sigval t)
(void)t; // suppress unused warning
changed = 1;
value--;
int main(void)
int ch;
timer_t tid;
struct itimerspec its = 0;
struct sigevent se = 0;
se.sigev_notify = SIGEV_THREAD;
se.sigev_notify_function = timer;
its.it_value.tv_sec = its.it_interval.tv_sec = 1;
timer_create(CLOCK_REALTIME, &se, &tid);
timer_settime(tid, 0, &its, NULL);
initscr(); raw(); noecho(); nodelay(stdscr, TRUE);
for (;;)
ch = getch();
if (ch != ERR)
if (ch == 'q') break;
changed = 1;
value++;
if (changed)
changed = 0;
move(0, 0);
printw("%d ", value);
move(0, 0);
refresh();
endwin();
answered 1 hour ago
pmg
81k996164
81k996164
add a comment |Â
add a comment |Â
Ritika is a new contributor. Be nice, and check out our Code of Conduct.
Ritika is a new contributor. Be nice, and check out our Code of Conduct.
Ritika is a new contributor. Be nice, and check out our Code of Conduct.
Ritika is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52715808%2fhow-do-you-write-a-c-program-to-increment-a-number-by-keypress-and-auto-decremen%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Do not use delays
– P__J__
2 hours ago
Why not? If there's some adverse effect I don't know about, what alternative can I use to simulate a delay? Nested for loops are highly CPU consuming so I avoided that. I do not want the decrement to happen immediately because that woudn't give the user enough time to increment it in the first place.
– Ritika
2 hours ago
If you want to do multiple things at once (waiting for delay to finish and waiting for a keystroke), you might want to look into multithreading
– MemAllox
2 hours ago
If you know better do not ask
– P__J__
1 hour ago
2
Since you are calling
getch()
, and talk about the "console window", my guess is that you are programming on Windows? Is that correct? You need to state which environment you are using, since things like these are done differently in different operating systems, and it looks like some of the answers assume Linux instead of Windows.– Thomas Padron-McCarthy
1 hour ago