Program is printing late (c) [duplicate] - c

This question already has an answer here:
Why is C printing outputs late?
(1 answer)
Closed 7 years ago.
I wrote the following code (it is a caclulator which gets 1 of 3 operators (+/-/$) and 2 natural numbers (a,b) and calcultes (a op b) (a$b is defined to be a+(a+1)+...+(b-1)+b for a<=b and for a>b it is not defined):
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Please choose an operation (+/-/$): ");
char op;
scanf("%c", &op);
while (op != '+' && op != '-' && op != '$') {
printf("\nInvalid operation. Please choose again: ");
scanf("%c", &op);
}
int a;
int b;
char term;
printf("\nPlease enter the first operand: ");
int scanCheck = scanf("%d%c", &a, &term);
while (scanCheck != 2 || term != '\n' || a < 0) {
printf("\nInvalid number\n. Please enter the first operand: ");
scanCheck = scanf("%d%c", &a, &term);
}
printf("\nPlease enter the second operand: ");
scanCheck = scanf("%d%c", &b, &term);
while (scanCheck != 2 || term != '\n' || b < 0) {
printf("\nInvalid number\n. Please enter the first operand: ");
scanCheck = scanf("%d%c", &b, &term);
}
if (op == '$' && a > b)
printf("\nThe result is: Not Valid");
int result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '$':
result = 0;
while (a <= b) {
result += a;
a++;
}
break;
}
printf("\nThe result is: %d", result);
return 0;
}
My problem is that when I run the program it prints nothing. However, after giving the program an input (e.g +, 3, 4) it prints the lines it should have printed earlier (with the correct result). Why does this happen? How can I fix this? FYI I'm using eclipse Juno with minGW compiler.

You may want to add the '\n' at the end of your print statements instead of at the beginning: the buffers may not be flushed and will be delayed because of it.

Output is line buffered. Add a newline at the end of any printout. Or flush the buffer explicitly using fflush(stdout);
For some reason many C programmers like to print newlines at the start of each printout. My advice would be not to do it that way. Just put the newline at the end of each printout, and you'll save yourself lots of trouble:
printf("The result is: %d\n", result);

Related

How to insert a continue statement inside an if statement

My code is below. I am using C language. I want to repeat the action from the start if the user types Y but I am confused how can I make that happen.
I tried to look for a solution but the results doesn't fit for my program.
#include <stdio.h>
int main() {
int A, B;
char Y, N, C;
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2: ");
scanf ("%i", &A);
printf ("= %i", A + B);
printf ("\n\nAdd again? Y or N\n");
scanf ("%c", &C);
if (C == Y) {
//This should contain the code that will repeat the:
printf ("Enter value 1: ");
scanf ("%i", &B);
printf ("\nEnter value 2:
} else if (C == N)
printf ("PROGRAM USE ENDED.");
else
printf ("Error.");
}
You should just wrap your code inside a for loop:
#include <stdio.h>
int main() {
int A, B;
char Y = 'Y', N = 'N', C;
for (;;) { // same as while(1)
printf("Enter value 1: ");
if (scanf("%i", &B) != 1)
break;
printf("\nEnter value 2: ");
if (scanf("%i", &A) != 1)
break;
printf("%i + %i = %i\n", A, B, A + B);
printf("\n\nAdd again? Y or N\n");
// note the initial space to skip the pending newline and other whitespace
if (scanf(" %c", &C) != 1 || C != Y)
break;
}
printf("PROGRAM USE ENDED.\n");
return 0;
}
There are a lot of errors in your program.
Syntax error: please resolve it on your own.
There is no need for Y and N to be declared as character, you can use them directly as they are not storing any value.
NOW, there is no need for continue you can use while loop.
I have resolved your problem. Please take a look
Also, you are using a lot of scanf so there is an input buffer, a simple solution to it is using getchar() which consumes the enter key spaces.
#include <stdio.h>
int main()
{
int A, B;
char C = 'Y';
while (C == 'Y')
{
printf("Enter value 1: ");
scanf("%i", &B);
printf("\nEnter value 2");
scanf("%i", &A);
printf("= %i\n", A + B);
getchar();
printf("\n\nAdd again? Y or N\n");
scanf("%c", &C);
}
if (C == 'N')
{
printf("PROGRAM USE ENDED.");
}
else
{
printf("Error.");
}
}

how to choose an operator and show it

I don't know what is wrong wiht my program, i tried to enter the numbers from keyboard and enter any operator and sort them like "a+b", but I don't know if it is correct so far, I don't have errors, but when I enter an operator it shows "You did not enter an opperator" it goes straight to the else, I don't know why. If you could please help me, thank you!
int main()
{
int a, b;
int op;
int var = '+';
int var1= '-';
int var2= '/';
int var3= '*';
printf("Choose your 2 numbers: ");
scanf("%i", &a);
scanf("%i", &b);
printf("Choose your operator (+, -, *, /): ");
scanf("%i", &op);
if(op == var || op == var1 || op == var2 || op == var3)
{
printf("The correct order is: %i, %i, %i", a, op, b);
}
else
{
printf("You did not enter an operator");
}
return 0;
}
So, first of all it'd be better to declare your op variable as a char instead of int as you are trying to read a character from the keyboard and not an integer number. Indeed if your try to print out your op variable as it is in your code you'll find out that its value is 0.
After changing this you should also change all %i for that variable to %c. This though will give a problem when using scanf(), which is that it will look like it got skipped. This is because the scanf() will read the last \n from the user as the character and put it in your variable.
To fix this you just need to put a space before %c so that the scanf() will skip the first whitespace character and then read from the keyboard. You can find more detailed explanation about this here
Anyway down here there's the working code.
int main()
{
int a, b;
char op;
int var = '+';
int var1 = '-';
int var2 = '/';
int var3 = '*';
printf("Choose your 2 numbers: ");
scanf("%d", &a);
scanf("%d", &b);
printf("Choose your operator (+, -, *, /): ");
scanf(" %c", &op);
if(op == var || op == var1 || op == var2 || op == var3)
{
printf("The correct order is: %i, %c, %i", a, op, b);
}
else
{
printf("You did not enter an operator.");
}
return 0;
}

My code keeps skipping a part every iteration of a while() loop in C

After the first iteration of my loop, it becomes a disgusting mess.
The code is as follows:
#include <stdio.h>
int main()
{
double a, b; char op = 'a';
while(op != 'E')
{
printf("Insert operator: \n");
scanf("%c", &op);
printf("Insert first number: \n");
scanf("%lf", &a);
printf("Insert second number: \n");
scanf("%lf", &b);
switch(op)
{
case '+': printf("%lf \n", (a + b)); break;
case '-': printf("%lf \n", (a - b)); break;
case '*': printf("%lf \n", (a * b)); break;
case '/': printf("%lf \n", (a / b)); break;
}
op = 'a';
}
return 0;
}
The console looks like in the picture. 1
Transcript:
Insert operator:
+
Insert first number:
1
Insert second number:
2
3.000000
Insert operator:
Insert first number:
8
Insert second number:
-
Insert operator:
Insert first number:
2
Insert second number:
5
I'm new to coding and this is my first time on Stack Overflow, I'm sorry if I did something wrong like formatting my question. Thanks for helping!
You have two (actually 3) primary problems:
You fail to remove the '\n' left in stdin after the user presses Enter after entering b before attempting to read op again. The "%c" format specifier (along with "%[...]") does not ignore whitespace, so you must manually add a space before the " %c" in your scanf() format string so that the whitespace is ignored;
Your handling of op = 'a'; after the switch() statement ensures op never equals 'E' which you use to exit the while(op != 'E') loop. You should test whether op == 'E' after op is read and break the loop there if the user enteres 'E'. (which also means your loop can simply be while(1)
The biggest of all. You fail to check the return of any of your user-input functions scanf(). You cannot use any input function correctly (and especially scanf()) if you do not check the return. You must handle at minimum 3-cases, 1 - good input, 2 - a matching or input failure, and 3 - EOF. If you fail to check the return, you invite all types of nasty results like Undefined Behavior when you attempt to access the value of a variable after input failed or an infinite loop where a matching failure occurs, character extraction from the input stream ceases, and the offending character remains in your input stream unread.
To handle reading and validating op, you can do:
#include <stdio.h>
int main (void) {
double a, b; char op = 'a';
while (1) {
/* read and VALIDATE operator */
fputs ("\nInsert operator (+,-,*,/) : ", stdout);
if (scanf (" %c", &op) != 1 || op == 'E')
return 1;
/* validate op is one of + - * / */
if (op != '+' && op != '-' && op != '*' && op != '/') {
fputs ("error: invalid operator.\n", stderr);
return 1;
}
Then for each a and b, you can do:
/* read and VALIDATE first number */
fputs ("Insert first number : ", stdout);
if (scanf ("%lf", &a) != 1)
return 1;
/* read and VALIDATE second number */
fputs ("Insert second number : ", stdout);
if (scanf ("%lf", &b) != 1)
return 1;
(note: those are the bare minimum validations required and they don't accommodate any failure and recover, they simply check if input is valid or exits)
Putting it altogether, you can do something similar to the following:
#include <stdio.h>
int main (void) {
double a, b; char op = 'a';
while (1) {
/* read and VALIDATE operator */
fputs ("\nInsert operator (+,-,*,/) : ", stdout);
if (scanf (" %c", &op) != 1 || op == 'E')
return 1;
/* validate op is one of + - * / */
if (op != '+' && op != '-' && op != '*' && op != '/') {
fputs ("error: invalid operator.\n", stderr);
return 1;
}
/* read and VALIDATE first number */
fputs ("Insert first number : ", stdout);
if (scanf ("%lf", &a) != 1)
return 1;
/* read and VALIDATE second number */
fputs ("Insert second number : ", stdout);
if (scanf ("%lf", &b) != 1)
return 1;
switch(op) {
case '+': printf ("\n %g + %g = %g\n", a, b, (a + b)); break;
case '-': printf ("\n %g - %g = %g\n", a, b, (a - b)); break;
case '*': printf ("\n %g * %g = %g\n", a, b, (a * b)); break;
case '/': printf ("\n %g / %g = %g\n", a, b, (a / b)); break;
}
}
}
Example Use/Output
$ ./bin/scanf_char
Insert operator (+,-,*,/) : +
Insert first number : 4
Insert second number : 5
4 + 5 = 9
Insert operator (+,-,*,/) : -
Insert first number : 4
Insert second number : 5
4 - 5 = -1
Insert operator (+,-,*,/) : *
Insert first number : 4
Insert second number : 5
4 * 5 = 20
Insert operator (+,-,*,/) : /
Insert first number : 4
Insert second number : 5
4 / 5 = 0.8
Insert operator (+,-,*,/) : E
Look things over and let me know if you have further questions.
Your code is not skipping operator, but just in the 2nd while loop iteration receives \n, entered after "second number", in 1nd loop iteration. You need skip out all \n\r chars before operator. You can do it, for example, by adding do/while around sscanf(op), like:
10 printf("Insert operator: \n");
11 do
12 scanf("%c", &op);
13 while(op < 040);
Or, more nice solution:
1 #include <stdio.h>
2
3 int main()
4 {
5 double a, b; char op;
6 for( ; ; )
7 {
8 printf("Insert operator[+-*/], a, b: ");
9 fflush(stdout);
10 char buf[100];
11 fgets(buf, sizeof(buf), stdin);
12 sscanf(buf, "%c%lf%lf", &op, &a, &b);
13
14 switch(op)
15 {
16 case '+': printf("%lf \n", (a + b)); break;
17 case '-': printf("%lf \n", (a - b)); break;
18 case '*': printf("%lf \n", (a * b)); break;
19 case '/': printf("%lf \n", (a / b)); break;
20 case 'E': return 0;
21 }
22 }
23 }

my do-while is terminating instead of continuing my C program

When I'm trying to run without debugging the code everything runs smooth but as soon as I press Y so I can continue inputting numbers it terminates (gotta say I need help)
int main() {
int a;
char c;
do {
puts("dwse mou enan arithmo: ");
scanf_s("%d", &a);
if (a > 0) {
if (a % 2 == 0)
printf("the number %d is even \n", a);
else
printf("the number %d is odd \n", a);
} else {
printf("the program won't run with negative numbers \n");
}
printf("if you want to proceed press y or Y :");
c = getchar();
getchar();
} while (c == 'y' || c == 'Y');
return 0;
}
The character read by getchar() is the pending newline that was typed after the number but was not consumed by scanf_s.
You should consume this pending newline before reading the next character for the continuation test, which can be done easily in scanf with a space before the %c conversion specification:
#include <stdio.h>
int main() {
int a;
char c;
for (;;) {
printf("dwse mou enan arithmo: ");
if (scanf_s("%d", &a) != 1)
break;
if (a >= 0) {
if (a % 2 == 0)
printf("the number %d is even\n", a);
else
printf("the number %d is odd\n", a);
} else {
printf("the program does not accept negative numbers\n");
}
printf("if you want to proceed press y or Y: ");
if (scanf_s(" %c", &c) != 1 || (c != 'y' && c != 'Y'))
break;
}
return 0;
}

C Program - Basic Calculator

I'm trying to write a basic calculator program in C, and I'm almost there! I have one issue though, and it's concerning repeatedly querying the user for input.
I can get through my loop once, but even though the user inputs the correct character, my program still breaks out of the loop.
I'm fairly new to C, but I've done a decent amount of programming in Java, so I understand the functionality of loops, conditionals, and data types.
#include <stdio.h>
int main()
{
char yes;
int a, b, c, choice;
yes = 'y';
while(yes == 'y' || yes == 'Y')
{
printf("Enter first integer: ");
scanf("%d", &a);
printf("Enter second integer: ");
scanf("%d", &b);
printf("\nAdd(1), Subtract(2), Multiply(3), Divide(4): ");
scanf("%d", &choice);
printf("\n");
switch(choice)
{
case(1):
c = a + b;
printf("%d + %d = %d\n", a, b, c);
break;
case(2):
c = a - b;
printf("%d - %d = %d\n", a, b, c);
break;
case(3):
c = a * b;
printf("%d * %d = %d\n", a, b, c);
break;
case(4):
c = a / (float)b;
printf("%d / %d = %d\n", a, b, c);
break;
default:
printf("Incorrect choice. Try again.\n");
}
printf("\nAgain (Y/N): ");
scanf("%c", &yes);
}
return 0;
}
You need to consume the trailling newline, enter remains in the stdin buffer ready to be read by the next scanf.
Change
scanf("%c", &yes);
to
scanf(" %c", &yes);
The problem is that the newline character is left on the input after inputting a number to choose what operation to do. So when the user is asked if they want to do it again, the newline is taken instead of the y or n. I might be wrong, it's been a while since I've done some programming.
What worked for me to fix it was to put a little bit of code after the line
printf("\nAgain (Y/N): ");
Adding this bit right after the printf statement will remove the newline from the input and should do the trick.
while(getchar() != '\n')
getchar();
Maybe someone else can explain exactly why this works, I don't remember the specifics. It's a little thing that I found useful to remember, it comes up every now and again.

Resources