No way to input data when the program is running in NetBeans - c

I'm trying to execute a program from the book by K. N. King "C Programming, A Modern Approach, 2 Edition", in NetBeans 8.0.2, using MinGW compiler. The program looks like this:
#include <stdio.h>
int main(void) {
int height, length, width, volume, weight;
printf("Enter height of box: ");
scanf("%d", &height);
printf("Enter length of box: ");
scanf("%d", &length);
printf("Enter width of box: ");
scanf("%d", &width);
volume = height * length * width;
weight = (volume + 165) / 166;
printf("Volume (cubic inches): %d\n", volume);
printf("Dimensional weight (pounds): %d\n", weight);
return 0;
}
So, I press "Run Project", the program builds successfully without any errors, then it begins to run and nothing happens, no console or something like that appears to input data like height, length, etc.
In the output window, after the program builded, it begins to run and nothing is displayed in the window except for a thick cursor. When I press any button being in that window, the program ends and this is what is displayed:
Enter height of box: Enter length of box: Enter width of box: Volume (cubic inches): 0 Dimensional weight (pounds): 0
RUN SUCCESSFUL (total time: 6s)
I'm completely new to C, so I don't know, what should appear when the program runs. When launching programs written in Python the console appeared, and now I'm confused.
When I tried to debug, it builded successfully again and then the console appeared with the line: "Enter height of box: ", so it worked like I thought it should work, but I don't think this is the proper way to run programs.

stdio streams are buffered. You need to fflush() stdout before using stdin, if you want the output to be displayed before the program blocks waiting on input. Alternatively, you can end all output lines with '\n', as newline implicitly flushes the output.
Edit: If you're entering data that scanf() cannot match using %d, such as alphabetic characters, scanf() will fail. You can check for this failure by comparing the return value of scanf() with the number of matches you expected (one in this case). As it stands, you don't check for this, and the characters stay in the input buffer, where the next scanf() will again try and fail to match them.

Related

My Visual Studio Code won't run my code properly

I can't properly run/debug my code in VS Code using the C language. I've installed C/C++ package on VSC, Mingw & applied the path for Mingw. All my files are running .c format as well.
Only the last part of my code keeps crashing in VSC, when I run this same code on website compilers, it works!
Here is my code:
#include <stdio.h>
int main(void) {
int num1;
int num2;
printf("Enter a number: ");
scanf("%d", &num1);
printf("Enter another number: ");
scanf("%d", &num2);
printf("Answer: %d ", num1 + num2);
return 0;
}
That last printf is where VSC just shuts down the output window, so I never get to see the end result of my code. Anyone have any solutions to fix this? It'd be greatly appreciated!
When you run your console program from Visual Studio, it opens a terminal window, runs the program and the terminal window closes automatically when the program exits. This is a classic problem with the Microsoft Windows platform that they do not seem to care about despite millions of newbie programmers like you experiencing the same problem.
If you open the terminal window yourself, by running the CMD command from the start menu, you will be able to run your program manually after changing the current directory to that of the program binary.
To prevent the terminal window from closing immediately when running directly from Visual Studio, you should add 2 getchar(); statements before returning from main() to wait for user input and get a chance to see the output. Just reading a single byte with getchar() will not suffice because it will just read the pending newline entered by the user in response to the second prompt.
Also note that it is preferable to output a trailing newline to ensure the output is properly flushed on some legacy systems:
printf("Answer: %d\n", num1 + num2);
Here is a modified program you can test:
#include <stdio.h>
int main(void) {
int num1 = 0, num2 = 0;
printf("Enter a number: ");
scanf("%d", &num1);
printf("Enter another number: ");
scanf("%d", &num2);
printf("Answer: %d\n", num1 + num2);
getchar(); // read the pending newline
getchar(); // read at least another byte from the user.
return 0;
}
run you program from the console:
In the search box type cmd
cd \path_to_your_executable
run your program.

While running my code in MPI, the root process never executes despite following the correct syntax

While trying to execute my code written in C using the MPI Library, I encountered something very odd happening.
My code generates no syntax error yet when I try
mpirun -n 3 ./q4
I get this
hello
hello
hello
from the other side.
from the other side.
from the other side.
It seems to never enter the rank 0 process. I have no idea why this is happening. This code is structurally identical to some other samples that I have writtten (I can provide the entire code if need be)
However, if I were to type in any two random things after the sixth line, I get this
1213
123
Enter a length for the string that is divisible by the number of processes Number of vowels 27
I don't really know what to do to fix it except that I checked my code for logically errors, which there are none and even if they are, they are much later which means that at least the the code under the first if case should execute.
int main(int argc, char * argv[])
{
printf("hello\n");
int rank,m,size,num;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
printf("from the other side.\n");
char str[100];
if (rank == 0 )
{
printf("Enter a length for the string that is divisible by the number of processes ");
scanf("%d",&m);
scanf("%s",str);
}
.
.
In case it is relevant, I am running Ubuntu 18.04.
You need to add some fflush(stdout); after the last printf to force the text refresh.
When there is no \n in printf text, the text is not displayed immediately.
So you should write:
printf("Enter a length for the string that is divisible by the number of processes ");
fflush(stdout);
scanf("%d",&m);
....
Or simpler:
puts("Enter a length for the string that is divisible by the number of processes ");
scanf("%d",&m);
....
The puts is to print a message on a line (it creates a new line). And it's not buffered.
In case anyone ever reads this in the future, this is to add to what Matthieu said.
The code should be like this
if (rank == 0 )
{
printf("Enter a length for the string that is divisible by the number of processes \n");
fflush(stdout);
.
.
.

Netbeans 8.1 scanf() function does not work properly

I'm running Netbeans 8.1 on a Windows 10 x86 64-bit computer, I have the project's Run>Console Type set to Standard Output because neither internal nor external terminal have worked for me with any other source I've made--for which standard output had. In any case, here is the code I'm attempting to run:
int main(void){
float original_amount, amount_with_tax;
printf("Enter an amount: ");
scanf("%f", &original_amount);
amount_with_tax = original_amount * 1.05f;
printf("With tax added: $%.2f\n", amount_with_tax);
exit(EXIT_SUCCESS);
}
and here is the output:
3
Enter an amount: With tax added: $3.15
RUN SUCCESSFUL (total time: 4s)
As you can see, the scan function is reading in the number before the program even prints "Enter an amount:". Also, after I commented out the scanf function, it printed both printf statements as expected. I have been wrestling with this problem for a while now and any help is appreciated, thanks!
ISO/IEC 9899:201x:
Files
… When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line
character is encountered. …
Your standard output stream seems to be line buffered, which is most often so.
try printf("Enter an amount: ");fflush(stdout); – BLUEPIXY
That worked! Is this only necessary because I'm using the standard output as my run console?
No, other streams opened by your program may even be fully buffered.
And if so, should I just put it at the beginning of any program that
will use a function accessing the buffer?
Putting fflush(stdout) at the beginning of a program won't do, since it outputs only once what is already in the stdout buffer. But you can use setbuf(stdout, NULL) there.

Eclipse CDT with C running errors

so I've decided to install Eclipse to use for my C programming. I wanted to write a small program, just to test that everything works, however it seems that Eclipse won't let me scan in any C inputs. For any other program, that requires no input, it works fine but it seems for some reason Eclipse won't run any program that requires a use to input. I'm running the programs by going to Run->Run As-> Local C/C++ Applications. I've also tried running these programs through the command line, and they turn out fine. Any ideas?
Code:
#include <stdio.h>
int main(void) {
int length, width, height, volume, weight;
printf("Enter the length of box: ");
scanf("%d", &length);
printf("Enter the height of box: ");
scanf("%d", &height);
printf("Enter the width of box: ");
scanf("%d", &width);
volume = length * width * height;
weight = (volume+165)/166;
printf("Volume(cubic inches) %d\n", volume);
printf("Dimensional weight(pounds): %d\n", weight);
return 0;
}
Installed Packages:
After I try to run these programs, nothing appears in the console window, but after I press stop this is what comes out:
Here's a better pic: http://i.imgur.com/zgV1r.png
Try adding an fflush(stdout) after each of your printf() calls as suggested here.
Here is some more discussion of why fflush is required.

Why is scanf altering the execution order?

I'm capturing some user input and saving it to both a struct and a file.
For each field, I first write a prompt using printf, and then capture data to the struct using scanf, and finally write to file using fprintf.
The program works fine, but only on one computer, one scanf executes before its corresponding printf.
Here's the core of the problem:
printf("\n color: ");
scanf("%s",&robot1.color);
fputs(robot1.color, f);
fputs("\n",f);
printf("\n energy: ");
scanf("%d",&robot1.energy);
fprintf(f,"%d",robot1.energy);
fputs("\n",f);
printf("\n height: ");
scanf("%f",&robot1.height);
fprintf(f,"%.2f",robot1.height);
fputs("\n",f);
printf("\n weight: ");
scanf("%f",&robot1.weight);
fprintf(f,"%.2f",robot1.weight);
fputs("\n",f);
I tested it on two Windows PCs using Dev-C++, and on a Mac using GCC. One of the Windows machines is the one causing all this mess.
The correct execution (user input included) is:
color: red
energy: 100
height: 30.5
weight: 500.0
But in the troublesome computer, after I input the energy value, it shows nothing, and to continue I have to input the height value.
After that, I see the height and weight prompts, and finish by capturing the weight:
color: red
energy: 100
30.5
height:
weight: 500.0
The file is written correctly in all cases so, why is only one computer having trouble with scanf and printf?
The struct definition is:
typedef struct roboto
{
char name[10];
char color[10];
int energy;
float height;
float weight;
}robot;
I am guessing its an issue with stdout not being flushed before the user is being prompted for input. To fix this you could try flushing stdout after each print statement using fflush(stdout);. For example:
printf("\n color: ");
fflush(stdout);
scanf("%s",&robot1.color);
fputs(robot1.color, f);
fputs("\n",f);
The standard output is buffered so you cannot be sure when it will be written.
Call fflush(stdout) to force the output to be written after calling printf, then you can be sure that the output will be written.
Maybe checking the return value from scanf would give you some clues. Ignoring that value is just asking for trouble.

Resources