#include <stdio.h>
int main()
{
int i=0;
if (getc(stdin));
{
i ;
printf("%d\n",i);
}
return 0;
}
This is what I have tried ! But it is not working please help me with this for my assignment!
I tried reading enter key as an input and if that is read. i is incremented and printed
CodePudding user response:
Trying out your code with the "if" test (and removing the semicolon) only results in the reading and printing of the value of "1". Your question intimates that there should be some type of continuous looping, but the way your code is structured, that will not happen. The premise of your question would point at using a "while" loop along with some type of test to exit the "while" loop and end the program. With that as the basis, following is a snippet of code that would get you closer to your desired outcome.
#include <stdio.h>
int main()
{
int i=0;
char test;
while (1)
{
test = getc(stdin);
if (test == 'Q') /* To provide a way to gently end the execution of the program */
{
break;
}
if (test == '\n') /* Could use this test of the newline character to detect when enter has been pressed */
{
i ;
printf("%d\n",i);
}
}
return 0;
}
Some points to note.
- A "while" loop was added to allow for a user to continually enter in characters and press the enter key (or just press the enter key). The value of "1" within the "while" loop equates to a Boolean value of "true" so this in effect makes this an endless loop.
- A test was added to determine if the user enters the character "Q" which provides a way to break out of the loop and end the program - such a test and subsequent break is a customary method for exiting an endless loop.
- A test was then added for sensing the pressing of the enter key - when sensed, the counter value is incremented and printed.
With that, following is some test output at the terminal.
@Dev:~/C_Programs/Console/LineNumber/bin/Release$ ./LineNumber
1
2
3
4
5
6
7
Q
@Dev:~/C_Programs/Console/LineNumber/bin/Release$
Give that a try to see if it meets the spirit of your project. One last note. This issue probably should be categorized as a "C" program issue and not a "C " issue.