这是我上一篇文章的后续文章,现在询问如何将另一个字符串数组添加到我以前的基于文本的物品商店。上次有人很有帮助,告诉我可以通过数组跟踪价格和物品名称,虽然我仍然不完全理解,但我正在尝试使用。我还应该序言我的代码非常简单,因为我才刚开始编程
我的代码如下,
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int string_to_price(string item)
{
//The array/s that's catching me up.
string items[] = { "Matchbox", "Wool Hat", "Heavy Coat", "Canned Food" };
int prices[] = { 50, 125, 250, 25 };
string description[] = { "They're cheap, and they'll keep you warm.\n", "A nice, handknit, cozy hat. Thank my ma for that!\n", "This coat'll keep you cozy through the night no matter the situation!\n", "It don't taste too good, but it'll last you a lifetime. Eat up!" };
for (size_t i = 0; i < (sizeof items / sizeof *items); i++)
{
if (0 == strcmp(items[i], item))
{
return prices [i];
}
}
//Item not available
return -1;
}
int main(void)
{
//Dialogue, then ask for item selection
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);
//Get item price from selection
int price = string_to_price(select);
//Return dialogue based on selected item.
if (-1 == price)
{
printf("We aint got that, pal.\n");
}
else
{
char c = get_char ("That %s'll cost ya %i buckaroonies. %s You want it?\n", select, price, description);
}
}
字符串
我肯定做错了什么,因为我得到一个错误,告诉我“描述”不是一个声明的字符串。
1条答案
按热度按时间8hhllhi21#
你的数组(
items
,prices
,description
)对于string_to_price
函数来说是 * 本地 * 的-这意味着它们只能在该函数内部访问。main
看不到它们。有几个修复。此外,函数应该返回索引,而不是价格,这样你就可以访问其他数组。
使数组全局化:
字符串
由于全局值不受欢迎,另一种选择是将它们本地化到
main
并作为参数传递:型
最终,你将学习结构,这将允许你把数据放在一起。
型