Using putchar and printf together in the same C Program? - c

I've written a small C program where I wanted to display the numeric ASCII value that corresponds to certain key presses.
My code follows. The problem is, after running the program, it accepts input, but doesn't do anything else. It doesn't even reach the first printf statement. I can't figure out what the issue is - is there a problem with mixing the getchar() function with the printf() function in the same program?
#include <stdio.h>
int main() {
const int numKeys = 256;
int keys[numKeys];
int i;
for (i = 0; i < numKeys; i++) {
keys[i] = 0;
}
printf("\n Start pressing some keys!\n\n");
int c;
while ((c = getchar()) != EOF) {
printf(" CAPTURED: %d\n", c);
keys[c]++;
}
printf("\n\n ** RESULTS ** \n\n");
for (i = 0; i < numKeys; i++) {
if (keys[i] != 0) {
printf(" Key with value %d was called %d times.", i, keys[i]);
}
}
}
I should clarify that I have a Windows XP Pro machine, with Cygwin installed. I use Cygwin for my development space, so I wonder if there is something different when running this type of program in that environment.

I found the problem. I think you want to use
while ((c = getchar()) != EOF && c != '\n')
Instead if you want to have it print the results after the person hits enter/return.

problem 1 : getting to printf(" CAPTURED: %d\n", c); without having to press the Enter key
solution : is by using getche() in while loop.
problem 2 : getting to 'printf("\n\n ** RESULTS ** \n\n");' or essentially breaking while loop?
solution : you cannot. you will never get EOF as long as you read from keyboard.
workaround : close stdin or use a escape character other than EOF.
EDIT : workaround2 :
->use getchar() itself. but to print those entered char u need to press Enter key. now on windows ctrl+z gives EOF but this should be the **FIRST** input on the line after you press Enter key. well this is not a good solution.
if you want a "Press key display times pressed scenario. there is just no simple way(AFAIK)"

I believe that the first printf statement gets executed, but due to buffering is not displayed on the screen immediately. Use fflush(stdout) to send the contents of the buffer to the screen. Ie:
printf("\n Start pressing some keys!\n\n");
fflush(stdout);

Related

Unexpected output while reading string from a keyboard

This program is returning something which I'm not able to comprehend. Attached is the screenshot of the O/P simple program to find number of spaces, tabs, etc.
What am I missing?
#include <stdio.h>
#include <string.h>
int main() {
int count[] = { 0, 0, 0 }; /* 0 is spaces, 1 is tabs and 2 for newline. */
int string;
printf("Enter the paragraph: \n");
while ((string = getchar()) != EOF) {
if (string == ' ')
count[0]++;
else if (string == '\t')
count[1]++;
else if (string == '\n')
count[2]++;
}
printf("There are %d Spaces.\n", count[0]);
printf("There are %d Tabs.\n", count[1]);
printf("There are %d Newlines.\n", count[2]);
return 0;
}
From the screenshot it appears you typed Ctrl-Z to signal the end of file to your program. While this works in legacy systems such as MS/DOS and the Windows terminals, this key combination has a different meaning on unix systems such as linux: it causes the current process to be suspended by its the running shell parent. The process can be resumed later with the fg command.
To signal the end on file on this system, you should type Ctrl-D instead.
Your program should produce the expected result then. The code seems OK, albeit it is quite confusing to name string an int variable that gets a single byte from getchar(). Such a variable is usually named c.
If you want to send an EOF in order to stop reading you should use CTRL+D.

unexpected result when counting word length in c using for loop

i am learning c language, and the program is about counting no of characters.
here is code
#include <stdio.h>
int main(void) {
// your code goes here
double nc;
for (nc=0;getchar() != EOF;nc++);
printf("%.0f\n", nc);
return 0;
}
input
''
input in none.
the output which I am getting is 1.
online compiler result
shouldn't be output equal to 0, not 1.unable to understand why is this coming.
thanks
if you put a bit more effort in yor programming adding couple of lines of code everything would be clear:
#include <stdio.h>
int main(void) {
// your code goes here
int nc;
int c;
for (nc=0;(c = getchar()) != EOF;nc++)
{
printf("The char is '%c' code: 0x%02x\n", c >= 32 ? c : '.', c);
}
printf("%d\n", nc);
return 0;
}
https://ideone.com/jfGK7h
And the mistery is solved. You have pressed the enter in the ideone input box and you have a new line there.
How did you input that input?
If you hit the <enter> key at the keyboard, then you got a single \n char, leading to that response.
Try this:
$ a.out
<Ctrl-D>
0
$ _
($ is the prompt, and <Ctrl-D> is the way to produce no input from a unix terminal) Of course, a.out is the name of your program (you didn't show how it is called)
BTW, why do you end the output in a \t in printf() ??? \t is a tab character, not a new line.... 8-.

getchar() returns a character that isn’t a newline after I press enter

This is the code:
#include <stdio.h>
int main()
{
int i = 0;
while(getchar() != '\n') {
printf("\n%d\n", i);
i++;
}
printf("second printf: %d\n", i);
return 0;
}
The expected ouput after I press enter only is:
second printf: 0
instead of:
0
second printf: 1
Why is this happening ?
I am on linux Ubuntu MATE.
So I got some information about anas firari's environment by reading his other questions. This involves some measure of physic debugging.
You are getting input of \r\n when you type a newline because your terminal is in raw mode. Older shells used to choke on this by treating \r as something that isn't whitespace, but newer ones actually work ok.

Count number of blanks, spaces, and tabs in C [duplicate]

This question already has answers here:
How to send EOF via Windows terminal
(3 answers)
Closed 5 years ago.
I am working through K&R's exercises right now and I am at the one where you count the number of blanks, spaces, and tabs using the C language. I have built the following code:
#include <stdio.h>
#include <stdlib.h>
/*Write a program that counts blanks, tabs, and newlines*/
int main()
{
int c, numblanks, numtabs, numnewlines;
numblanks = 0;
numtabs = 0;
numnewlines = 0;
printf("Enter some text and press \"Enter\"\n");
while ((c = getchar()) != EOF) {
if (c == ' ')
++numblanks;
if (c == '\t')
++numtabs;
if (c == '\n')
++numnewlines;
}
printf("The total number of blanks is %i\n", numblanks);
printf("The total number of tabs is %i\n", numtabs);
printf("The total number of new lines is %i\n", numnewlines);
}
I am using Codeblocks and the built-in GCC compiler that is installed with it on a Windows 10 OS. When I run the program, I type some text into the program window that pops up and press "Enter" and nothing happens. I am not sure why. I was wondering if someone could help me get another pair of eyes on my code to see if there is something I am missing. Here is an image of what happens in the program when I run it:
Program window with typed text, but no reaction
I have not tried your solution but sometimes this can happen when the program is finished, the terminal closes. Try to put a getchar at the end of your program.
printf("Enter key to exit");
getchar();
This can help after string input (but sometimes require creating loop with getchar() and checking the result of this function)

Why is this C for-loop not working properly?

int main()
{
int t, i;
int *nums;
scanf("%d", &t);
nums = malloc(t * sizeof(int));
for(i = 0; i < t; i++)
{
scanf("%d", &nums[i]);
}
printf("hey");
}
For some reason, it hangs, waiting for more input! Any ideas?
This code is correct, except for the fact that you're not freeing your memory (not a big issue for this simple code) and you're not checking scanf for errors, which may be the cause of your problem.
A better implementation with error checking and correct memory handling is described below:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int t, i, ret;
int *nums;
ret = scanf("%d", &t);
if(ret != 1)
{
/* something wrong */
}
nums = malloc(t * sizeof(int));
if(nums==NULL)
{
/* memory error */
}
for(i = 0; i < t; i++)
{
ret = scanf("%d", &nums[i]);
if(ret != 1)
{
/* something wrong */
}
}
free(nums);
printf("hey");
return 0;
}
Just a guess here...
But I'm guessing you ran it and entered :
4
1234
For example, you put in 4 and then 1234 and it hangs. Well, that would be because 1234 is the first number and not 4 distinct numbers so its waiting for the second number. You have to press enter or some such delimiter between each number.
Try this set of inputs instead:
4
1234
29
4
5
You should get :
hey
Pro grammatically, you should be checking return values from your function calls. Make sure malloc didn't return zero. Make sure scanf returns the number of inputs you expected to read. Add in printouts to make sure the values it read in are what you expected/wanted to read in.
EDIT :
Guessing you have a typo in the program which isn't displayed here. such as :
scanf("%s", &t);
Or you are getting the 'hey' and just not seeing it.
[ov#MARVIN sotest]$ ./a.out
5 5 4 3 23 1
hey[ov#MARVIN sotest]$
See the 'hey' is sort of hidden in my prompt because you are missing the '\n' new line in the printout?
Remember to flush when you are done.
In chat, OP's comments "No... BTW, if I add a printf in the loop that prints the current input, it prints everything except from the last one...". This hinted that the issue was on the final output.
The following sends data out to be printed. But stdout is typically buffered. Actual output may not occur until sometime later. Output is flushed when 1) output contains an end-of-line '\n', 2) fflush() is called 3) the program ends. I am surprised output did not appear when the program ended, but possibly OP's true code differs from the post.
printf("hey");
Change to
printf("hey\n");
Or #Cool Guy
printf("hey");
fflush(stdout);
BTW: This is also hinted in #Diversity answer.
Note: Always a good idea to check the result of scanf()
// scanf("%d", &t)
if (1 != scanf("%d", &t)) Handle_BadInput_or_EOF();

Resources