Reputation: 25
So i have written this:
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
int main() {
float balance;
char type;
printf("Card balance: ");
scanf("%f", &balance);
do {
printf("Vehicle type: ");
scanf("%c", &type);
if (type != 'B' || type != 'b' || type != 'C' || type != 'c' || type != 'T' || type != 't') {
printf("Incorrect vehicle type!");
}
} while(type != 'B' || type != 'b' || type != 'C' || type != 'c' || type != 'T' || type != 't') ;
system("pause");
return 0;
}
And when i try to run it those errors come up:
1.
scanf
: This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use_CRT_SECURE_NO_WARNINGS
.2.system undefined; assuming extern returning int
Upvotes: 1
Views: 78
Reputation: 16540
1) when calling scanf()
and family of functions, always check the returned value (not the parameter value) to assure the operation was successful.
2) the '"%f" format specifier will leave the newline
('\n') character in the input stream. Then the "%c" format specifier will be reading the newline ('\n') on the first iteration and every odd iteration of the loop.
3) the posted code is (effectively) saying `!(type==B and type==b and type==c ...) But a variable can only hold one value at a time. so the posted code will not properly loop. Suggest something like:
do {
...
if( 1 != scanf(" %c", &type) ) { // handle error }
if (type != 'B' && type != 'b' && type != 'C' && type != 'c' && type != 'T' && type != 't') {
printf("Incorrect vehicle type!");
}
} while(type != 'B' && type != 'b' && type != 'C' && type != 'c' && type != 'T' && type != 't') ;
Note the leading space in the format string for the call to scanf()
, which will consume leading white space.
Note the checking of the returned value from scanf()
to assure the operation was successful.
Note the leading &
on the type
parameter, as scanf()
requires the address of its' parameters, so it will know where to place the result of the input/conversion operations.
4) system("pause");
is not portable as not all OSs recognize the "pause" as a valid command line input. suggest using:
while( int ch =getchar() && ch != '\n' && ch != EOF );
getchar();
Upvotes: 0
Reputation: 5773
scanf
takes the address of a variable as argument. So, you need to do
scanf("%f", &balance);
scanf("%c", &type);
For system
, you need to include stdlib.h
Upvotes: 2
Reputation: 131
The first problem indicates that you need to give the address of the variable, or the pointer to the variable you want the scanf to return its results. Try this instead:
scanf("%f", &balance);
Edit: missing & character :)
Upvotes: 1