簡體   English   中英

C ++字符串數組和布爾

[英]C++ string array and bools

我目前正在嘗試制作一個小食譜應用。 我制作了一個包含10個字符串和10個布爾值的string數組。 例如,當我鍵入Cinnemon時,我想使_Cinnemon真。 我怎么做?

另外,此書寫是否正確,還是我可以做得更好? 我是編程新手。

最后,我該如何解決它,所以無論是小寫字母還是大寫字母都沒有什么可說的?

這是代碼:

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]

如果要在代碼解釋收貨內容的地方添加一些邏輯,則可以在開頭添加一個枚舉,該枚舉為每個索引賦予邏輯名稱:

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;
}  

重要說明:

我認為您應該了解原始代碼的一些問題:

  • 無論while (i = -1)會永遠循環,無論i的值是多少。 =是賦值運算符(即,將-1復制到i並在條件中評估i的值)。 從C / C ++開始時,這是最常見的錯誤:您當然是while (i==-1)的比較。

  • ingredient == "Exit" || "exit" ingredient == "Exit" || "exit"是有效的語法。 但是這種情況總是正確的。 它絕不表示“不滿是退出還是退出”。 為此,您需要寫成ingredient == "Exit" || ingredient =="exit" ingredient == "Exit" || ingredient =="exit"

  • 您的循環結構將無法成功搜索。 特別是如果輸入的雜物不符合預定義的列表...

此任務有不同的方法。 例如,您可以使用布爾數組和帶有將用作數組索引的成分名稱的枚舉。

您可以使用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 ingredients\n" << 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 >>因為某些成分名稱由多個單詞組成。

另外,您應該進行不區分大小寫的搜索。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM