如何让C在get_string输入后检查少数特定字符串?

c6ubokkw  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(104)

我在CS50的第二周,作为编程的新手,我想知道是否有一种方法可以像整数一样检查特定的字符串?
我正在做一个基于文本的项目商店作为语法的实践,遇到了不知道如何输入人们想要的项目并将其重定向到确认或拒绝+项目描述的问题。
我很想把我尝试过的东西包括进来,但是考虑到我不知道从哪里开始,我还没有什么东西可以放在这里。我目前的代码,为了我正在做的事情的简单性。

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int buckaroonies = 500;
    printf("Hey chum, welcome to the item shop. You've got a handful 'o coin on ya, huh?\nYou came to the right place, we got the best wares in town!\n\n");
    printf("Store:\n\nMatchbox - 50\nWool Hat - 125\nHeavy Coat - 250\nCanned Food - 25\n");
    string select = get_string ("What'll it be? You have %i buckaroonies, pal.\n", buckaroonies);
}

字符串

gkl3eglg

gkl3eglg1#

考虑到你正在学习CS50,一个很好的书签页面是https://manual.cs50.io/,它包含了你在任何类Unix操作系统(例如https://man.openbsd.org/)上都能找到的手册的简化版本。
扫描此页面,在string.h下,您将看到:

strcmp页面解释了该函数的 prototype

int strcmp(string s1, string s2);

字符串
它会返回
0如果s1s2相同
在使用中,这看起来像

if (0 == strcmp("Matchbox", select))
{
    puts("That will be 50 buckaroonies!");
}
else if (0 == strcmp("Wool Hat", select))
{
    puts("That will be 125 buckaroonies!");
}


在实践中,你可能希望以某种方式 * 循环 * 这些选项,而不是手工编写每个比较。考虑下面的例子,使用两个等长的 * 数组 * 表示商店中的物品及其价格:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int string_to_price(string item)
{
    string items[] = { "Matchbox", "Wool Hat", "Heavy Coat", "Canned Food" };
    int prices[] = { 50, 125, 250, 25 };

    for (size_t i = 0; i < (sizeof items / sizeof *items); i++)
    {
        if (0 == strcmp(items[i], item))
        {
            return prices[i];
        }
    }

    /* item does not exist */
    return -1;
}

int main(void)
{
    int buckaroonies = 500;
    printf("Hey chum, welcome to the item shop. You've got a handful 'o coin on ya, huh?\nYou came to the right place, we got the best wares in town!\n\n");
    printf("Store:\n\nMatchbox - 50\nWool Hat - 125\nHeavy Coat - 250\nCanned Food - 25\n");
    string select = get_string ("What'll it be? You have %i buckaroonies, pal.\n", buckaroonies);

    int price = string_to_price(select);

    if (-1 == price)
    {
        puts("We aint got that, pal.");
    }
    else
    {
        printf("That %s will cost ya %i buckaroonies!\n", select, price);
    }
}
Hey chum, welcome to the item shop. You've got a handful 'o coin on ya, huh?
You came to the right place, we got the best wares in town!

Store:

Matchbox - 50
Wool Hat - 125
Heavy Coat - 250
Canned Food - 25
What'll it be? You have 500 buckaroonies, pal.
Canned Food
That Canned Food will cost ya 25 buckaroonies!

的字符串
稍后,当您更习惯时,用一个structures数组替换这两个数组会更健壮。
标签:How do I determine the size of my array in C?

相关问题