Reputation: 631
It is suppose that to an entry such as:
1 1 524 5 true -1
where the first parameter is the idOrder
, the second parameter is the number of products in idOrder
, the third parameter is a code, the fourth parameter is the amount of products, the fifth parameter is a boolean to distinguish the product and the sixth parameter is the final mark.
It should return an output such as:
524 -1 5
where the first parameter is the code of the product, the second parameter is the final mark and the third parameter is the amount of products.
This is my code:
#include <stdio.h>
typedef enum {false, true} bool;
int main()
{
const int END = -1;
int idOrder, numProducts, idCodeProduct, amount, total, temp;
bool generic, endSeq;
scanf("%d", temp);
/*printf("%d ", temp);*/
idOrder = temp;
endSeq = temp == END;
if (endSeq != true) {
total = 0;
scanf("%d", &temp);
numProducts = temp;
scanf("%d", &temp);
idCodeProduct = temp;
scanf("%d", &temp);
amount = temp;
scanf("%d", &temp);
generic = temp;
if (generic == true) {
total = total + amount;
printf("%d", idCodeProduct);
}
}
printf("%d ", END);
printf("%d ", total);
return 0;
}
When I run this code, it doesn't return anything at all and I don't know why.
Upvotes: 0
Views: 138
Reputation: 154322
1) Remove trailing space in formats as suggested by @Joachim Pileborg.
2) Change temp
to &temp
as suggested by @Anonymous
3) Do not try to read "true" as an int
as comment ed by @BLUEPIXY. Read as string and convert.
4) No need for temp
@Joachim Pileborg
5) Always check scanf()
results.
6) Initialize total
7) Avoid your own typedef enum {false, true} bool;
, use stdbool.h
8) Simplify
int main() {
const int END = -1;
char tf[6];
int idOrder, numProducts, idCodeProduct, amount;
int total = 0;
bool generic, endSeq;
for (;;) {
if (scanf("%d", &idOrder) != 1)
Handle_BadInput();
endSeq = idOrder == END;
if (endSeq)
break;
if (scanf("%d%d%d%5s", &numProducts, &idCodeProduct, &amount, tf) != 4)
Handle_BadInput();
if (strcmp(tf, "true") == 0)
generic = true;
else if (strcmp(tf, "false") == 0)
generic = false;
else
Handle_BadInput();
if (generic) {
total = total + amount;
printf("%d ", idCodeProduct); // add space
}
}
printf("%d ", END);
printf("%d ", total);
return 0;
}
Upvotes: 1
Reputation: 409472
The problem is that you have a trailing whitespace in the format codes to scanf
. While this causes scanf
to read and discard whitespace, it also causes scanf
to read until it finds a non-whitespace. If there's nothing more to read, then scanf
will wait indefinitely for more input.
Drop the trailing space in the format and it should work better. As long as you are scanning for normal strings or numbers you have to remember that scanf
actually skips leading whitespace automatically.
I recommend you read e.g. this scanf
reference.
Upvotes: 2