C++字符串数组和布尔

C++ string array and bools

本文关键字:布尔 数组 字符串 C++      更新时间:2023-10-16

我目前正在尝试制作一个小食谱应用程序。我制作了一个包含10个字符串和10个布尔的string数组。例如,当我键入Cinnemon时,我想使_Cinnemon为true。我该怎么做?

此外,这写得对吗?或者我能把它写得更好吗?我对编程很陌生。

最后,我该如何修复它,使它无论是小写字母还是大写字母都没有任何可说的地方?

这是代码:

std::cout << "Welcome, type your ingredients " << std::endl;
std::string ingredients[10]{"Cinnemon", "Milk", "Eggs", "Butter", "Tomatoes", "Salt", "Backing Soda", "Suggar", "Chicken", "Honny"};
bool _cinnemon, _milk, _eggs, _butter, _tomatoes, _salt, _backingSoda, _Suggar, _chicken, _honny;
std::string ingredient;
int i = -1;
while (i = -1) {
    std::cin >> ingredient;
    i++;
    while (i < 9)
    {
        if (ingredient == ingredients[i]){
            std::cout << "Type another if you have any more igredients else type Exit" << std::endl;
            i++;
        } if (ingredient == "Exit" || "exit"){
            return 0;
        } else{
            i++;
        }
    }
} 

尝试将硬编码字符串映射为布尔值。所以你可以很容易地改变它们。

map<string, bool> m;
m["blah"] = false; // Initialize to false
// Later, you can change it by
m["blah"] = true;
// To look up a value, simply do
if(m.count("blah") && m["blah"]) {
  // "blah" is true and do whatever you want to do here
}

至于忽略大小写的字符串比较,您可以编写自己的函数来实现这一点,例如

#include <cctype>  // This is where tolower() is defined
bool stringCmpIgnoreCase(string a, string b) {
  if(a.length() != b.length())
    return false;
  for(int i = 0; i < a.length(); i++)
    if(tolower(a[i]) != tolower(b[i]))
      return false;
  return true;
}

我知道您正在学习,所以我将避免使用高级数据结构,如映射和集合,这些数据结构将用于实际应用程序。

我提出的解决方案只是使用一个布尔值数组。对于找到的每个字符串,我都在同一索引处设置布尔标志。以下是它的工作原理:

std::cout << "Welcome, type your ingredients " << std::endl;
const size_t maxind = 10;  // avoid hard coded size !  
std::string ingredients[maxind]{"Cinnemon", "Milk", "Eggs", "Butter", "Tomatoes", "Salt", "Backing Soda", "Suggar", "Chicken", "Honny"};
bool hasindegrient[maxind]{}; // make a table to know which one is present
std::string ingredient;
bool stopit = false;  // exit requested ? 
while (! stopit) {
    std::cin >> ingredient;
    int i;
    for (i=0; i<maxind; i++) 
        if (ingredient == ingredients[i]){
            hasindegrient[i] = true; // <================ set flag of indegrient
            break;
        }
    if (i==maxind) { // here we didn't find it ! 
        if (ingredient == "Exit" || ingredient == "exit")
            stopit = true;
        else  
            std::cout << "Indegrient not found !" << std::endl;
    if (!stopit)
        std::cout << "Type another if you have any more igredients else type Exit" << std::endl;
    }
} 
for (int i=0; i<10; i++)  // display the indegrient list
    if (hasindegrient[i])
        cout << ingredients[i]<< " "; 
cout << endl;

使用这种方法,每个布尔值都是匿名的:每个hasindegrient[i]要么为true,要么为false,但没有名称。因此,就其本身而言,它没有任何意义。但在这个程序中,如果hasindegrient[i]为真,则意味着indegrients[i]在收据中。

如果你想在代码解释receipe内容的地方添加一些逻辑,你可以在开头添加一个枚举,为每个索引提供一个逻辑名称:

enum {IDG_Cinnemon, IDG_Milk, IDG_Eggs, IDG_Butter, IDG_Tomatoes, IDG_Salt, IDG_Backing_Soda, IDG_Suggar, IDG_Chicken, IDG_Honny };

您可以将此枚举的每个元素理解为一个常量。正如你所看到的,我遵循的顺序与字符串表中的顺序相同。这样就可以编写代码,例如:

if (hasindegrient[IDG_Butter]) {
    std::cout << "Take care of your cholesterol" << std::endl;
}  

重要备注:

我认为你应该知道你的原始代码的一些问题:

  • 无论i的值是多少,while (i = -1)都将永远循环。=是赋值运算符(即-1复制到i,i的值在条件中求值)。这是从C/C++开始时最常见的错误:您当然是指while (i==-1),它是一个比较。

  • ingredient == "Exit" || "exit"是一个有效的语法。但这个条件总是成立的。它绝不意味着"要么退出,要么退出"。为此,您可以编写ingredient == "Exit" || ingredient =="exit"

  • 您的循环结构将不会在搜索中成功。特别是如果输入的索引不符合预定义的列表。。。

此任务有不同的方法。例如,您可以使用bool数组和枚举,其中包含将用作数组索引的成分名称。

您可以使用std::bitsetstd::vector<bool>

您可以使用成对的std::pair<std::string, bool>. 阵列

你也可以使用std::map。

这是一个演示程序

#include <iostream>
#include <map>
#include <string>
int main() 
{
    std::map<std::string, bool> ingredients =
    {
        { "Cinnemon", false }, { "Milk", false }, { "Eggs",false },
        { "Butter", false }, { "Tomatoes", false }, { "Salt", false },
        { "Backing Soda", false }, { "Suggar", false }, { "Chicken", false },
        { "Honny", false }
    };
    std::cout << "Welcome, type your ingredientsn" << std::endl;
    std::string ingredient;
    bool selected = false;
    while ( std::getline(std::cin, ingredient ) )
    {
        if ( ingredient == "Exit" | ingredient == "exit" ) break;
        if ( selected = ( ingredients.count( ingredient ) != 0 ) )
        {
            ingredients[ingredient] = true;
        }
        else
        {
            std::cout << "Invalid ingredient." << std::endl;
        }
        std::cout << "Type another if you have any more igredients else type Exit" << std::endl;
    }
    if ( selected )
    {
        std::cout << "You selected ingredients:"  << std::endl;
        for ( const auto &p : ingredients )
        {
            if ( p.second ) std::cout << p.first << std::endl;
        }
    }
    return 0;
}

考虑到您必须使用函数std::getline而不是operator >>,因为有些成分名称由几个单词组成。

此外,您应该进行不区分大小写的搜索。