Output behaviour of scanf and printf in C (Eclipse Console) - c

Excuse me if this might be painfully obvious, but I've not found an answer to this so far. I just started learning some C basics after mostly working with Java so far.
I've tried to follow this tutorial and am currently very confused with how printf and scanf behave in the Eclipse console.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char character;
printf("Enter a character: ");
scanf("%c", &character);
printf("Character: %c",character);
return 0;
}
What I'm expecting to happen, based on the linked tutorial:
Enter a character: _
I'm expecting this line to be printed to the console and then wait for my input where I put _ as a placeholder, before then printing Character: _. This behaviour is how I'd expect it in Java.
What actually happens:
On running my code, the console stays completely empty. At first I spent 2 hours thinking the program was simply not executing. Luckily I then noticed that the empty console was simply my prompt to give my user input. Once I input a character and press enter, the printf's are written into the console like so:
a
Enter a character:
Character: a
Is this behaviour normal and my expectations for the behaviour are just plain wrong? If so, how would I go about realizing my desired behaviour of first being presented with the prompt to input a character?

Related

Can't indicate EOF through keyboard in Windows (Netbeans) , in a C program [duplicate]

I have been learning C from K&Re2. And the above code is what is mentioned in Pg18(Letter counting program), which I ran for confirmation purposes. I tried entering few characters and press ENTER, but it was not working. Then I heard about CTRL+Z,CTRL+C or CTRL+D with ENTER for End Of File. I tried it in NetBeans console, but it was not working. I tried \0 and \n too, pity it was not working too. I have searched for this, but all seemed to have solved the problem with CTRL+Z,CTRL+C or CTRL+D with ENTER method. I can't understand what is the problem here.
PS: I use Windows 7
Sorry for not inserting code directly. Here is it-
#include <stdio.h>
#include <stdlib.h>
int main() {
long c = 0;
while (getchar() != EOF) {
++c;
}
printf("%ld", c);
return 0;
}
In the image, I have not initialized value of long c. Sorry for that. This program is running, but the methods I use for EOF doesn't work out.
EDIT:
I have tried compiling in NetBeans, and then running the resulting .exe in cmd rather than in NetBeans console. CTRL+Z seems to work! Do you guys have any idea why it doesn't work in NetBeans console?
getchar() stores characters in buffer until you press enter key. After enter key is pressed,first character is taken from buffer if no subsequent variable is being assigned.As you used while loop it will take until \r\n.so you have to press enter key + ctrl+z to reach EOF.
Windows Only
Product Version: NetBeans IDE 8.2 (Build 201609300101)
Updates: NetBeans IDE is updated to version NetBeans 8.2 Patch 2
Run > Set project configuration > Customize...
Category = Run
Console Type = External Terminal
External Terminal Type = Command Window
Click Apply then OK
Run project
To send EOF press ENTER then CTRL+D Or Press CTRL+D twice

Eclipse; Escape Sequences don't work?

I am doing a basic C tutorial. In an example this code was given to introduce escape sequences:
#include <stdio.h>
int main()
{
printf("This is a \"sample text\"\n");
printf("\tMore text\n");
printf("This is getting overwritten\r");
printf("By this, another sample text\n");
printf("The spa \bce is removed.\n");
return 0;
}
The console output is expected to look like this:
This is a "sample text"
More text
By this, another sample text
The space is removed.
Instead, I get this:
This is a "sample text"
More text
This is getting overwritten
By this, another sample text
The spa ce is removed.
I am using Eclipse Cpp Oxygen on Windows and the Cygwin toolchain to compile und run the code. I don't know what I'm doing wrong and I thought I'd ask here for help.
The console built in to Eclipse does not support the \r, \b (and \f) characters.
There is a long standing bug 76936 for this which has been open for 14 years. But doesn't look like being fixed.
In linux you example works exactly as you expect. Probably in windows the \r is considered like \n.
Instead on linux terminal the \r put (correctly) the cursor on the first char of the row.

C/C++ BEGINNER - fgets with stdin causing unexpected 'loop' results

I'm a programming student who's only really looked at Java up until now. This semester is our first time using C and I'm having a lot of trouble wrapping my head around some of the simplest functions. I really have no idea what I'm doing. I couldn't even get Eclipse to work correctly with MinGW so I eventually gave up and reverted to Netbeans.
So basically I'm trying to use fgets to read user input for a switch-case menu, but I can't get fgets to work in even the simplest situations. To troubleshoot I tried copying a simple fgets example from online, but even that is giving me unexpected results.
When I run the code below it just runs an infinite empty loop (it does not prompt for user entry at all, it does not accept any user entry, it just 'runs' forever and the console remains blank). When I delete the fgets line and remove the other reference to the 'name' variable it works as you would expect (prints the user entry prompt and then ends).
Example code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
char name[10];
printf("Who are you? ");
fgets(name,10,stdin);
printf("Glad to meet you, %s.\n",name);
return(0);
return (EXIT_SUCCESS);
}
Any advice would be appreciated!
Other info:
I am running - Win 8 (poor me) & Netbeans IDE 8.0 (with MinGW)
When creating my C project I select File=> New Project=> C/C++=> C/C++ Application
EDIT: When I run the program I have tried:
1) right clicking the project file => Run; and
2) clicking the big green arrow in the netbeans ribbon;
.... neither works.
This code should work, but for you to be able to input anything, you need to run in in a proper terminal.
My guess is that you're running it inside your IDE and it's set to use pipes as stdin/stdout. Instead you should start cmd.exe and run the program in there (you'll have to navigate to the correct directory first).
Or, optionally, there might be a setting in your IDE to run the program using cmd.exe or with a builtin terminal.
A final note. You should learn to use sizeof whenever a buffer size is required. I.e. change this:
fgets(name,10,stdin);
to
fgets(name, sizeof(name), stdin);
Also, please use spaces to make your code more readable. Reading code is a big part of programming.
1) You might want to flush the file, after printf("Who are you? "); with fflush(stdout);
2) You have two return statements (which is harmless).
Other than that, your code is fine.
It works perfect - but you might want using fflush(stdin); before the fgets() call.
Also remember fgets return a string with '\n' after a user input - solved simply with name[strlen(name)-1]='\0'; - which is basically putting NULL as an "end of a string" symbol, basically you remove the '\n'.
And DO NOT change 10 to sizeof(name) - it doesn't matter at all, basically it's even supposedly worse as you can't use this in functions properly (sizeof(name) won't always match the length and would be the size of the pointer).
You should try compiling with MinGW if it didn't work, it will surely work on it.
A reminder: fgets() may let you enter MILLION characters, but it will take the first 10, in this case, at least.

Using C and trying to create a mad lib.

As my title says I'm a new programmer learning C. This is my second day programming and I need help fixing this problem in my code. I'm making a mad lib and while no errors come up the first scanf takes 2 lines rather than the 1 every other scanf uses.
Here's the code:
#include <stdio.h>
int main()
{
char verb[20];
char loc[20];
char noun1[20];
char noun2[20];
char adj[20];
/* The following is the part where you input words. It sets them as strings (named word1-5, as stated above)*/
printf("Welcome to Mad Libs! \nAnswers can only be one word long. \nPlease enter a verb.\n");
scanf("%s\n",verb);
printf("Now enter a location!\n");
scanf("%s\n",loc);
printf("Now enter a noun!\n");
scanf("%s\n",noun1);
printf("Now enter another noun!\n");
scanf("%s\n",noun2);
printf("Now please enter an adjective!\n");
scanf("%s\n",adj);
/* It all comes together here. The code is supposed to take the strings set previously and put them into this story. */
/* The dashes and various /n's are there to make the final Mad Lib easier to read */
printf("\n\nHere is your Mad Lib:\n------------------------------ \nHolly %s down to the %s.\nOnce she got there she bought some %s and ate it!\nAfterwards, Holly brought it home and let her %s eat it.\nHolly is a %s girl!\n------------------------------ \n",verb,loc,noun1,noun2,adj);
return 0;
}
It was made using a combination of Vi and Sublime Text 2 on Ubuntu.
Like I said, I'm not getting any errors when compiling and everything seems to be in order, the problem is that once I run it in the Terminal I have to enter the first answer (answer to "Welcome to Mad Libs! Answers can only be one word long. Please enter a verb.") twice and it takes both of them.
Please try running it yourself (it should work in both OS X and Linux as a .c file) if you're confused as to what I mean, I honestly don't know how to describe the error very well. It makes me input the first answer twice and causes problems when showing the final mad lib.
Just use scanf("%s", ...), not scanf("%s\n"). The \n doesn't get there until later. (Oh, and this is also a good way to get buffer overflows, by the way, so you might consider using fgets, et. al.)
The way it's working right now is:
You type a line and press Enter. scanf gets the line, but without the \n, so it's still waiting.
You type the next line and press Enter. scanf now has the \n at the end of the previous line and uses that string. The first line was read, the second line is now in the buffer, and scanf is awaiting another \n that already exists.
GOTO 2
And that has the effect of shifting all of the answers by one.

Why does Eclipse fail on this scanf() command when the Command Prompt executes it fine?

I'm new to C. Here's my code:
/* Using scanf() */
#include <stdio.h>
int main(void) {
int iDec1, iDec2, iDec3;
printf("Enter three decimals:\n");
scanf("%d,%d,%d", &iDec1, &iDec2, &iDec3);
printf("Your decimals are %d, %d and %d.", iDec1, iDec2, iDec3);
return 0;
}
It works in the Command Prompt, but when I run it through Eclipse it doesn't do anything. After hitting stop, this appears in the Console output:
Enter three decimals
Your decimals are 3, 2147344384 and 2147344384.
What the...? How come it works fine outside Eclipse but not inside Eclipse?
So, this thread might help you out. Yes, it's for Java, not C, but the last post on this thread outlines how to get input to work in eclipse console. This may just come down to how you run your program.
If the info in the link doesn't help, please post the steps you take to execute your program (which menu options you use etc. Also post eclipse version). I'll try to replicate.
fflush(stdout); did the trick.
you can use fflush(stdout); after the print cmd so it will refresh and u will get your input screen.

Resources