Я довольно новичок в C, и я пытаюсь понять, используя строки и strcmp
, чтобы сравнить две строки в операторе if
.Использование strcmp в операторе if
Моя цель состоит в том, чтобы иметь возможность запускать другую функцию в зависимости от того, что пользователь ввел.
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
void gasbill();
void electricitybill();
int main()
{
char input[20];
const char gasCheck[4] = "gas";
const char electricityCheck[13] = "electricity";
printf("Your bills explained!\n\n");
printf("In this application I will go through your gas and electricty bills.\n");
printf("I will explain how each of the billing payments work, \nand the calculations that go on,\n");
printf("to create your bill.\n\n");
printf("Please choose a bill to get started with:\n- gas\n- electricity\n\n");
fgets(input, 20, stdin);
if (strcmp (input, gasCheck)== 0){
printf("\nPreparing to run Gas bill!\n\n");
system("PAUSE");
system("cls");
gasbill();
system("PAUSE");
}
else if (strcmp (input, electricityCheck)== 0){
printf("\nPreparing to run Electricity bill!\n\n");
system("cls");
electricitybill();
system("PAUSE");}
else {
printf("\nError exiting...\n\n");
system("PAUSE");
}
return 0;
}
void gasbill()
{
float balanceBroughtForward, gasThisQuarter, subTotalPerQuarter;
char poundSign = 156;
printf("******Your gas bill, explained!******\n\n\n");
printf("Hello, and welcome to your gas bill, explained. Let's get started.\n");
printf("Please enter the balance brought forward from your previous statement: \n\n%c", poundSign);
scanf("%f", &balanceBroughtForward);
printf("\nHow this works:\n- The money that you did not pay last quarter for your gas bill\nhas been added to this quarterly payment\n\n");
printf("\nNext let's add this to the amount of gas you have spent this quarter. \n(how much gas have you used so far in this billing period?)");
printf(": %c", poundSign);
scanf("%f", &gasThisQuarter);
printf("\n\nNow what? The two values that you have entered\n(balance brought forward
and gas spent this quarter)\nare added together, %c%3.2f + %c%3.2f\n", poundSign,
balanceBroughtForward, poundSign, gasThisQuarter);
subTotalPerQuarter = (balanceBroughtForward + gasThisQuarter);
printf("This is");
}
void electricitybill()
{
printf("Empty");
system("PAUSE");
}
Когда он запускает оператор if, он всегда выполняет функцию gasBill, а не функцию electricBill.
Заранее спасибо.
Попробуйте положить нуль в конце вашей Const символ вручную. Это может устранить расхождение. – Magn3s1um
Используя немного менее раздутую версию, служащую в качестве примера, код выше работал для меня. Я получаю газ, электричество или ошибку, в зависимости от того, что я пишу. – JugsteR