【问题标题】:Using strcmp in an if statement在 if 语句中使用 strcmp
【发布时间】:2013-05-15 12:42:13
【问题描述】:

我是 C 的新手,我试图理解使用字符串和 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 函数而不是electricalBill 函数。

提前致谢。

【问题讨论】:

  • 尝试手动将 null 放在 const char 的末尾。这可能会解决差异。
  • 使用稍微不那么臃肿的版本作为示例,上面的代码对我有用。我会得到汽油、电力或错误,具体取决于我写的内容。

标签: c string strcmp


【解决方案1】:

fgets 将返回一个以换行符结尾的字符串 (\n)。来自其文档

从流中读取字符并将它们作为 C 字符串存储到 str 直到 (num-1) 个字符被读取或换行符或 到达文件末尾,以先发生者为准。

您可以测试尾随换行符并将其去掉

fgets(input, 20, stdin);
size_t len = strlen(input);
if (input[len-1] == '\n') {
    input[len-1] = '\0';
}

或改为使用scanf 读取用户输入。

scanf("%19s", input);

顺便说一句

const char gasCheck[4] = "gas";
const char electricityCheck[13] = "electricity";

可以更容易和安全地声明为

const char *gasCheck = "gas";
const char *electricityCheck = "electricity";

(这种形式节省了将字符串文字复制到堆栈变量中的操作。更重要的是,如果您硬编码太小的数组长度,它可以消除潜在的错误来源。)

【讨论】:

  • Altought,我会避免使用 scanf,因为它会导致安全问题和错误,因为它可以写入超过字符串的大小。
  • 嗯... +1 指出fgets(),-1 使用臭名昭著的scanf() 来读取用户输入。用户输入中的空格可能会给您带来与预期不同的东西,例如...
  • @user1115057 "%19s" 的格式字符串最多可读取 19 个字符(加上空终止符),因此保证不会超出 input 的末尾
  • @simonc 所以在弄乱了你的不同建议之后,我没有运气,决定回到最初的样子。我仍然可以运行错误和gasbill,但电力不工作。所以我取出了煤气单的 if 语句部分,所以当我输入“gas”时,我得到了错误;正如预期的那样,但电力仍然无法运行它也会返回错误。编辑:我按照您的建议将 const 字符更改为指针(我认为它们被称为),谢谢。
  • 但是使用 %19s 并不安全,因为我们依赖于函数的解析能力。使用安全函数比使用不安全函数并尝试给他一些可以使其更安全的参数更安全。另外,由于 scanf 需要解析出来,它会使用更多的资源。
【解决方案2】:

fgets() 从标准输入读取字符,直到看到换行符或 EOF,如果看到换行符,它将存储在数组中。无论如何,fgets() 将空字符附加到数组。

所以如果你想用换行符结束你的输入,我的小改动就在这里,改变这个

const char gasCheck[4] = "gas";
const char electricityCheck[13] = "electricity";

const char gasCheck[5] = "gas\n";
const char electricityCheck[14] = "electricity\n";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2014-09-30
    • 2021-07-16
    相关资源
    最近更新 更多