I did part of this code for a class exercise and the code is working but i do not really understand what is happening in a particular piece.
Can anyone please explain this part:
if(scanf("%d%c", &num1, &term1) != 2 || term1 != '\n'){
printf("ERROR! You should type an integer e.g 5, 80, 100\n");
} else { ....
The complete code is :
#include <stdio.h>
int main(){
int num1,num2;
char term1,term2;
printf("Type your first integer\n");
if(scanf("%d%c", &num1, &term1) != 2 || term1 != '\n'){
printf("ERROR! You should type an integer e.g 5, 80, 100\n");
} else {
printf("Type your second integer\n");
if (scanf("%d%c", &num2, &term2) != 2 || term1 != '\n'){
printf("ERROR! You should type an integer e.g 5, 80, 100\n");
}
printf("\n%d", num1);
for (int i=0; i<num1; i++) {
printf(" *");
}
printf("\n");
printf("%d", num2);
for (int j=0; j<num2; j++) {
printf(" *");
}
}
}
The exercise was to make a program requesting 2 integers values and making a horizontal bar graph with the two values.
Thanks.
scanf()returns the number of terms it successfully received. You’re asking for two terms, so you’re comparing the result to ensure both were received. You’re then checking the character term to ensure it was a carriage return, so you know the user did not type any other text after entering the numeric term.I strongly agree with @Vlad’s comment about reading the documentation. If you post for help on questions that can be resolved yourself without any real effort, you’re doomed when you get exposed to more complicated things.