C Scanf Command Won't Run - c

I am a new learner to the C language. I am trying to figure out how to use scanf. This is my code so far.
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?");
scanf(" %c", &lastInitial);
}
When I run this code (I'm using VS Code), it shows that the file is running, but nothing shows up. When I go to the top to click the run button again, it says this code is already running. If I stop the run, delete the scanf line and run again, the file runs and displays "What is your last inital?" I am confused as to why adding scanf to the file stops the printf and doesn't allow any user input.

You might have run into a little intricacy with how printf works. When you run printf("What is your last inital?");, this text does not end with a newline (\n) character. As a result, some environments might not display it right away, delaying it until you printf a complete line or until the program ends. This is done for efficiency, since the internal steps to actually get output to your screen are a bit expensive.
When you remove the scanf, the program ends right after the printf; as the program is ending any text that's still waiting to be displayed gets sent to the screen by the built-in shutdown routines in the C standard library. However, when the scanf is included, the text gets buffered/delayed, and doesn't ever get sent to the screen sine the program is stalled waiting for user input. You can force the output to be sent immediately using a newline:
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?\n");
scanf(" %c", &lastInitial);
}
Or if you don't want a newline, you can tell the C standard library to explicitly send all output text right away:
#include <stdio.h>
#include <string.h>
int main() {
char lastInitial;
printf("What is your last inital?");
fflush(stdout);
scanf(" %c", &lastInitial);
}

When you run the program, you should switch from "OUTPUT" to "TERMINAL".
You need to install the "Code Runner" extension.
Then go to File-->Preferences-->Settings in the search write code runner, and below will appear some settings of code runner, you need to find Run In Terminal, and turn it on.
THAT'S ALL :)

Related

Application files made using CodeBlocks won't run outside the IDE

I've been learning programming with C and have made some starter programs using CodeBlocks. The problem is that I can't run the application files that are saved in bin\debug by double right clicking on them. Instead, I have to open the project file and hit "Run" or "Build and Run" to do so. Is there a way to fix this?
Firstly, "double click" means "double (left) click" and not "double (right) click".
Even if your machine does support "double right click" to open a file, the following could be a problem.
Consider a small program like this:
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
You can see its results when you run it inside the IDE because it waits for you to "press any key" before terminating it.
But when you run it outside the IDE, the program is terminated immediately at the end of main. The program will open, execute, and terminate before even you realizing it. It happens very quickly. In case of programs dealing with user inputs, you can see the intermediate results though.
Solution:
An easy fix is to add getchar() to the end of main. It will wait for you to press the enter key in order to quit the console application.
#include <stdio.h>
int main()
{
printf("Hello World");
getchar(); // <-- add this line of code
return 0;
}
You can also have a more controlled termination by making your own exit function.
For example, if your program leaves a newline in the buffer before calling the getchar, it would consume the '\n' and not wait for you to press the enter key. In that case, you should clear the input buffer:
// clear the input buffer
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
// then call getchar
getchar();

Where is scanf() reading input from, if not from the keyboard?

I'm a novice programmer getting introduced to C and I'm missing something fundamental about the way my scanf() works. I want to read a single int from the keyboard with code like this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int userBookSelection;
scanf("%i", &userBookSelection);
printf("Printing userBookSelection: %i", userBookSelection);
return EXIT_SUCCESS;
}
When I run the code, the console stays black until I stop debugging. There is never a cursor waiting for keyboard input. When I stop debug I can see this output in the console, same every time:
Printing userBookSelection: 2130567168
I'm debugging in Eclipse with MinGW GCC compiler on Windows. The code syntax seems to be correct -- is it possible there's something wrong in my build path to make this happen? I need to know why scanf() isn't reading for keyboard input.
So I've gotten a line of code from my professor which takes care of this bug -- whether it's a necessary solution particular to Eclipse and/or MinGW I'm not sure. In any case, here's the code with the additional line:
int main(void) {
int userBookSelection;
setvbuf (stdout, NULL, _IONBF, 0);//<---The magic line
scanf("%i", &userBookSelection);
printf("Printing userBookSelection: %i", userBookSelection);
return EXIT_SUCCESS;
}
I'd appreciate any additional wisdom on what's going on, what setvbuf() is doing and how scanf() works more fundamentally.

File path as user input in C

I couldnt find specific answer to my question. I am really low level, just started and had a class in which I learned to create file from the CodeBlocks. Took code with me home but it wont work because its not on the same computer. So, the idea was to make something that will allow user to choose path for the newly formed .txt file. When, instead of s, I manually insert "c:\example.txt" or something like that, the code creates a file "example.txt" but when I send it as input it simply wont. Why?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *a=NULL;
char s[50];
puts("Enter the path of the file: ");
fgets(s,50,stdin);
a=fopen(s,"w");
if(a==NULL)
exit(1);
else
printf("Successful input");
}
So the entire problem was the fgets function which adds the \nat the end? Is there any other idea to make this work?
You can replace the
fgets(s,50,stdin);
with
scanf("%49[^\n]%*c", s);
- this reads input excluding the \n into s, as long as its size allows, and consumes the \n, so that it doesn't get into the way of possible later input.

C console output hidden while awaiting input

Hi I'm trying some C coding on Eclipse, and I had a problem:
I am trying to print some text, however, while awaiting input from the user, the text actually fails to appear until AFTER the user has input.
Here is an example of what I mean:
TEST
#include <stdio.h>
#include <stdlib.h>
int main(void){
char c[5];
printf("test\n"); //PRINTING 'test' BEFORE i have to enter code
fgets(c, 5, stdin);
printf("You entered: %s\n", c);
return 0;
}
OUTPUT:
dog (this is what i typed)
test
You entered: dog
Rather than appearing BEFORE I am prompted to enter code, the "test" printf only appears AFTER I have entered the code.
Probably this text to print is still waiting in the buffer (that's an optimization, to group data to write to make it more efficient). To make sure everything from buffer gets out to the console you should flush it like this
fflush(stdout);
or you can use a function that does not use buffering like (on linux)
write()

getche clears the screen after pressing enter

I am experimenting with character input functions in C.Following is the program I am running interchanging getch and getche function calls for experimenting.
#include <stdio.h>
#include <conio.h>
#define MAX_CHARS 255
int main(){
//getche experiments
char buffer[MAX_CHARS+1],ch;
int x = 0;
while(x<MAX_CHARS&&(ch=getch())!='\r'){//relacing getch here with getche
buffer[x++]=ch;
putchar(ch);
}
buffer[x]='\0';
printf("%s",buffer);
return 0;
}
When I run the program with getch(),I get to see the each character
printed as soon as I enter them through keyboard(thanks to
putchar),and the whole line once I press enter(thanks to printf
statement at last).So it is fine.
When I replaced getch with getche the only difference I expected was
I would get each of the characters I enter printed twice as soon as I
enter(since getche echoes the character to stdout) and print the line
at last after I press enter.But as soon as I press enter whole screen
is cleared and the line is printed.
Why is the screen getting cleared before printing at last?
Thank you
There's no way for us to know without knowing what your documentation for getche says. There is no such standard function. My guess would be that it writes to a different screen from the one printf writes to. The screen is getting cleared because you have switched from one screen (the raw 'console' screen you echoed to) to another one (the normal terminal your program's standard output is attached to).
What does your platform's documentation for getche say?

Resources