这是我编写的代码:
#include <stdio.h>
#include <string.h>
int main(void) {
char userService1[50];
char userService2[50];
int price1;
int price2;
printf("Davy's auto shop services\n\n");
printf("Select first service:\n");
fgets(userService1,13,stdin);
printf("Select second service:\n\n");
fgets(userService2,13,stdin);
printf("Davy's auto shop invoice\n\n");
if(strcmp(userService1,"Oil change") == 0){
printf("Service 1: Oil change, $35\n");
price1 = 35;
}
else if(strcmp(userService1,"Tire rotation") == 0){
printf("Service 1: Tire rotation, $19\n");
price1 = 19;
}
else if(strcmp(userService1,"Car wash") == 0 ){
printf("Service 1: Car wash, $7\n");
price1 = 7;
}
else if(strcmp(userService1,"Car wax") == 0 ){
printf("Service 1: Car wax, $12\n");
price1 = 12;
}
else{
printf("Service 1: No service\n");
price1 = 0;
}
if(strcmp(userService2,"Oil") == 0){
printf("Service 2: Oil change, $35\n\n");
price2 = 35;
}
else if(strcmp(userService2,"Tire") == 0 ){
printf("Service 2: Tire rotation, $19\n\n");
price2 = 19;
}
else if(strcmp(userService2,"Car") == 0 ){
printf("Service 2: Car wash, $7\n\n");
price2 = 7;
}
else if(strcmp(userService2,"Car") == 0 ){
printf("Service 2: Car wax, $12\n\n");
price2 = 12;
}
else{
printf("Service 2: No service\n\n");
price2 = 0;
}
int price = price1 + price2;
printf("Total: $%d\n", price);
return 0;
}
这是当前版本输出的内容:
Davy's auto shop services
Oil change -- $35
Tire rotation -- $19
Car wash -- $7
Car wax -- $12
Select first service:
Select second service:
Davy's auto shop invoice
Service 1: No service
Service 2: No service
Total: $0
输入:
Oil change
Car wax
这是代码的期望输出:
Davy's auto shop services
Oil change -- $35
Tire rotation -- $19
Car wash -- $7
Car wax -- $12
Select first service:
Select second service:
Davy's auto shop invoice
Service 1: Oil change, $35
Service 2: Car wax, $12
Total: $47
我不确定是否使用fgets()
正确分配了字符串,或者不确定是否正确比较了字符串。无论哪种方式,我都不知道如何解决。
答案 0 :(得分:0)
问题在于fgets在字符串末尾读取“ \ n”
一种快速的解决方法是将其包括在您的比较中:
Directory not empty @ dir_s_rmdir
或者您也可以像这样完全切掉“ \ n”:
Install
两种解决方案都能达到预期的效果。