我在理解下面的代码时遇到了一些麻烦。我不知道如何使用枚举声明函数(或者我可能错误地理解了我的赋值?)。
Uri uri = Uri.parse(
"android.resource://" + "com.program.shekh.abdalah.ot57man" + "/raw/" + "Bob music.mp3"
);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
vs
int words_starting_with()
如果有人可以给您快速的解释或指导我了解更多信息,将不胜感激。
(我不是在寻找书面代码,只是一个可以帮助我完成作业的解释就可以了)
答案 0 :(得分:0)
在这里,您被要求填充传递的变量num_word
并返回函数的状态,这是一种检查错误的常用方法:
enum Status {STATUS_OK, FILE_ERR_OPEN, NOT_FOUND};
enum Status words_starting_with(char const *dict, char letter, int *num_word)
{
FILE *f = fopen(dict, "r");
if (f == NULL)
{
return FILE_ERR_OPEN;
}
char str[100];
while (fgets(str, sizeof str, f))
{
if (*str == letter)
{
*num_word++;
}
}
return *num_word == 0 ? NOT_FOUND : STATUS_OK;
}
如您所见,enum
正在自我记录函数的结果,现在进行比较:
int num_word = 0;
switch (word_starting_with("dict.txt", 'a', &num_word))
{
case FILE_ERR_OPEN:
perror("fopen");
exit(EXIT_FAILURE);
case NOT_FOUND:
puts("dict doesn't contain words starting with 'a'");
break;
case STATUS_OK:
printf("%d words starting with 'a'\n", *num_word);
break;
}
使用
int num_word = 0;
switch (word_starting_with("dict.txt", 'a', &num_word))
{
case 1:
perror("fopen");
exit(EXIT_FAILURE);
case 2:
puts("dict doesn't contain words starting with 'a'");
break;
case 0:
printf("%d words starting with 'a'\n", *num_word);
break;
}
第一个版本更清晰,更不容易出错,因为您甚至可以更改enum
中常量的顺序,并且结果仍然有效,正如@KeevinBoone在评论中指出的那样,编译器可以执行一些其他检查:
switch (word_starting_with("dict.txt", 'a', &num_word))
{
case FILE_ERR_OPEN:
perror("fopen");
exit(EXIT_FAILURE);
case STATUS_OK:
printf("%d words starting with 'a'\n", *num_word);
break;
}
提高
warning: enumeration value ‘NOT_FOUND’ not handled in switch