'C for Dummies' getchar() function not working - c

I'm currently in the very early stages of learning C programming and am working my way through "Beginning Programming with C for Dummies" using Code::Blocks.
The first activity in Chapter 7, Fetching characters with getchar(), asks us to copy the code exactly as it's presented in the book; see below:
#include <stdio.h>
int main()
{
int c;
printf("I'm waiting for a character: ");
c = getchar();
printf("I waited for the '%c' character.\n", c);
return (0);
}
The output I get is:
I'm waiting for a character:
However according to the book, the output that I should be seeing is the character's ASCII code value. It then asks that I change the %c placeholder to %d to display the value, but still I get the same outcome as before. I could probably recite the code with my eyes closed I've checked it through that may times; I simply cannot see where I'm going wrong.
Am I right in thinking that the getchar() function isn't being recognized? Or that the code isn't being read after the first printf statement? Any guidance is welcome as I don't want to move on until I've understood the problem.

Please enter any key, then 2nd printf will show the result. getchar() is expecting input from user, controller reach at 2nd line & waiting for input.

Related

scanf seems to break my code (C programming) [duplicate]

This question already has answers here:
C/C++ printf() before scanf() issue
(2 answers)
Closed 1 year ago.
I'm programming a text-based adventure game for my C Programming class, but for whatever reason, the code seems to break whenever I try to use "scanf" to get a player's input. Everything will print onto the console perfectly fine, but then when I include the line "scanf("%d", playerInput), nothing will print out and the program will run endlessly. Anyone know why this is the case? Here's my code:
#include <stdbool.h>
#include <stdio.h>
int main()
{
printf("~ Doctor Crowley: Master of Death ~\n"); //Titlecard
//Introductory narration =================================================================================================
printf("\n- Narrator -\n");
printf("You are Doctor Jonathan Crowley, an archeologist and wizard from the Arcane University in Aeternum.\n");
printf("You awaken in your classroom on the first floor of the University. Last you remember, you were in your office\n");
printf("on the sixth floor of the University.\n");
// Player Actions (1) ========================================================================================================================
printf("\n1. Stand up\n");
printf("2. Look around\n");
printf("-------------------------------------------\n");
int playerInput; //player input variable
printf("--> ");
scanf("%d", &playerInput);
return 0;
}
First of all make sure to write '&' before any variable in scanf. If you don't write that, it will crash and force you to end the program. Then as you write in your code it just input number and will put that in variable playerInput, and nothing more. You didn't print anything after scanf, so nothing will happen after that. For example you can write printf("%d",playerInput); after that and it will print the number that is in playerInput.

Simple C program won't run. Crashes in CMD

I'm new to programming in C and I'm trying to build and execute my first programs. My first program was Hello, World printed in the CMD like many of you. It worked great. Now it's onto bigger and better projects though and I'm having a weird issue.
I'm trying to make a basic addition calculator using standard IO operations (scanf and printf) and it won't function properly.
My program asks for 2 numbers to be input by the user and it will then display the output of said calculation. The program executes flawlessly until the scanf expression comes into play. After I input my 2 numbers to be added the CMD prompt just closes without warning and never spits out an answer or the text I have to be displayed afterward.
I tried multiple solutions to fix this problem including copying and pasting the source code directly from the website I was learning from, even their perfect code nets the same outcome..just a crash before an output is displayed. I'm posting today because I'm wondering where my issue is coming from because I'm just not sure why this program won't execute as it's supposed to. Thanks in advance and heres the code I'm working with:
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d", &a, &b);
c = a + b;
printf("Sum of the numbers = %d\n", c);
return 0;
}
Once console application returns from main method, the associated console window closes automatically. I assume you are using Windows OS. In that case add a system("pause"); before your return 0; statement.
For platform independent solution you can just show a prompt to user and wait for a key press before returning from main. As #chux pointed out in comment any character remaining in input buffer (enter from scanf in this case) must be cleared.
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d", &a, &b);
c = a + b;
printf("Sum of the numbers = %d\n", c);
//clear input buffer
int d;
while ((d = getchar()) != '\n' && d != EOF) { }
printf("Press ENTER key to Continue\n");
getchar();
return 0;
}
CMD prompt just closes without warning and never spits out an answer
Seems like you are opening a new terminal on Windows machine. I compiled the code and it works. Your program closes just after printing the answer so you simply cannot see it. Stop it artificially before the end. To prove it add the following line directly before return:
scanf("%c", &a);
This will result in stopping the program and waiting for input. You will need to enter another number which will essentially be ignored but will stop the program so you can see the output. This is not a good target solution though due to you need to enter some characters to go on and exit but it proves the point :)

fgets() breaks string into 2 lines

I am an absolute beginner to programming and I am starting with the C language. I am currently using the Beginning Programming with C for Dummies book by Dan Gookin.
When doing an exercise with fgets() the following occurred.
This is my code
#include <stdio.h>
int main()
{
char name[10];
printf("Who are you? ");
fgets(name,10,stdin);
printf("Glad to meet you, %s.\n",name);
return(0);
}
The expected result should be a name with a full stop at the end and what is happening is that the full stop carries over to the next line like shown below.
I am using the code blocks IDE on Ubuntu
You typed Miguel and then pressed ENTER. name now holds Miguel\n, in which \n stands for the ENTER you just pressed, since ENTER counts as a character too. If you want to remove it, you'll find the answer here.
You can use strtok(name, "\n")

scanf() not taking multiple inputs

Hi I just started learning C programming in gcc compiler on my Debian system. Here is the code
main()
{
fflush( stdin );
int a,b;
scanf("%d,%d",&a,&b);
printf("%d,%d",a,b);
}
The scanf doesn't take input for the second variable. I press 2 and then return key and it displays
root#debian:/home/wis# ./test
2
2,0root#debian:/home/wis#
I have used space and tab key also. Please help me.
You defined your scanf string as "%d,%d", so the program expect an input like 1,2.
If you give it only one digit and press Enter, it parses the first digit and leaves the second one untouched. It was assigned 0 on declaration, so that's what you are seeing when printing.
Your printf statement would benefit from an "\n" at the end, and your code snippet needs indentation. Please show your includes (#include <stdio.h>) next time, it makes it easier for us to compile and run the code.

Very basic example code of "The C Programming Language" doesn't work like expected?

I'm a middle experienced Java developer and have many problems learning the C language for my computer science study. I try it with the book "The C Programming Language" which many people seem to recommend.
But I've got problems with the simplest stuff like the EOF in combination with getchar(). Here's the code:
#include<stdio.h>
main()
{
int i = 0;
while (getchar() != EOF)
{
++i;
printf("Count of characters is %d", i);
}
}
I'm working with Mac OS X Lion and use the "cc" command with "./a.out" for running in terminal, like described in the book to run the file. And what I get is:
Always counting one character too much
the while loop never ends! it just waits for another input after reaching end of input ...
I really have no idea what could be the issue. Can someone help?
Always counting one character too much
That could be the newline (enter / return).
the while loop never ends! it just waits for another input after
reaching end of input
You are likely not signaling end of input. You should be using CTRL-D to do so.
When you type a character, such as "6" and you click enter (which is equal to \n), then the command "6\n" is sent, so it is 2 characters. If you just press enter, then 'i' will be increased by 1.
The EOF means end of file and its equivalent to ctrld+D. It is useful if you read a text file. Else it is the same as saying "Forever".

Resources