Coding in visual studio code
#include<stdio.h>
int main(){
char firstLetterofName;
int numOfVisits;
float priceOfDrink; //Creating the variables leaving them empty for now
float total;
printf("Hello! What is your name?n");
scanf("%c", &firstLetterofName); //Asking for an inputting the first letter of users name
printf("How many times have you visited Starbucks in a monthn");
scanf("%d", &numOfVisits); //Asking and inputting number of visits
printf("What is the price of the drink you order?n");
scanf("%f", &priceOfDrink); //Asking and inputting price of drink
total = priceOfDrink * numOfVisits;
printf("Wow %c! You have spent $%d on Starbuck!", firstLetterofName, total);
return 0;
}
First attempt using full name Terminal outputs
PS C:C Cpp> cd "c:C Cpp" ; if ($?) { gcc test.c -o test } ; if ($?) { .test }
Hello! What is your name?
Logan
How many times have you visited Starbucks in a month
What is the price of the drink you order?
Wow L! You have spent $0 on Starbuck!
Second attempt using only first letter
PS C:C Cpp> cd "c:C Cpp" ; if ($?) { gcc test.c -o test } ; if ($?) { .test }
Hello! What is your name?
L
How many times have you visited Starbucks in a month
5
What is the price of the drink you order?
2.0
Wow L! You have spent $0 on Starbuck!
PS C:C Cpp>
Expected output is Wow L! You have spent $10.0 on starbucks
For the name part it is suppose to only take the first letter.
2
Answers
With input
"Logann"
, code scans in the'L'
as thefirstLetterofName
with the"ogann"
reamaining instdin
for the next input function.With input
"ogann"
,scanf()
fails and returns 0.numOfVisits
was not changed. Code unfortunately did not not check the return value ofscanf()
to test success.To quickly discern
scanf()
troubles, checkscanf()
return values for success.Do not rely on the user to enter compliant text. Robust code watches out for too much data, not enough data, non-numeric data, etc. User input is evil.
Consider using
fgets()
to read a line of user input and then parse the resultant string.Use fflush(stdin) to flush the input stream. Availabe in gcc