Я только начал учиться программировать на C, не могу избавиться от ошибки. Вот моя программа:
/* This program rolls two dice and presents the total. It then asks the user
to guess if the next total will be higher, lower, or equal. It then rolls
two more dice and tells the user how they did. */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int dice1, dice2, total, total1= 0;
char ans[25], dans[25];
char higher[] = "HIGHER", lower[] = "LOWER", equal[] = "EQUAL";
//the following 3 lines, throws the dice and adds them.
dice1 = (rand() % 5) + 1;
dice2 = (rand() % 5) + 1;
total = dice1 + dice2;
//the next few ask the question.
printf("Will the next number be higher, lower or equal to %d ?\n", total);
puts("Type higher, lower or equal.");
// scanf("&s", ans); //had to remove this line, because apparently we can't use &s to get the string input
fgets(ans, 25, stdin);
strcpy(dans, strupr(ans));
//the next few throw the dice two more times
dice1 = (rand() % 5) + 1;
dice2 = (rand() % 5) + 1;
total1 = dice1 + dice2;
/*All of these check if the user input matches the actual output and
then tells the user if he/she was right.*/
printf("The upper string is %s.\n", ans);
if ((ans == higher) && (total1 > total))
{
printf("You're right, it is higher!\n");
}
else if ((ans == lower) && (total1 < total))
{
printf("You're right, it is lower!\n");
}
else if ((ans == equal) && (total1 = total))
{
printf("You're right. they are equal!\n");
}
else
{
printf("Your prediction was wrong.\n");
}
}
Ошибки, которые я получаю:
test.c: 25: 22: ошибка: неявное объявление функции 'Strupr' недопустимо в C99 [-Werror, -Wimplicit-function-декларация]
strcpy(dans, strupr(ans)); ^
test.c: 25: 22: ошибка: несовместимое целое число с преобразованием указателя с передачей 'int' параметру типа 'const char *' [-Werror, -Wint-conversion]
strcpy(dans, strupr(ans)); ^~~~~~~~~~~
/usr/include/string.h:129:70: примечание: передача аргумента параметру '__src' здесь extern char * strcpy (char * __ restrict __dest, const char * __ restrict __src)
^
test.c: 33: 18: error: сравнение массивов всегда возвращает false [-Werror, -Wtautological-compare]
if ((ans == higher) && (total1 > total)) ^
test.c: 37: 23: error: сравнение массивов всегда возвращает false [-Werror, -Wtautological-compare]
else if ((ans == lower) && (total1 < total)) ^
test.c: 41: 23: error: сравнение массивов всегда возвращает false [-Werror, -Wtautological-compare]
else if ((ans == equal) && (total1 = total))
Пожалуйста, помогите мне с ошибками.
Также,
Strupr должен находиться в
stdlib
, почему я все еще получаю сообщение об ошибке?Когда я конвертирую строку в строку в верхнем регистре, как она меняется на int?
Почему я не могу использовать
%s
вscanf
? (Я использовал это раньше)
Спасибо.
strupr()
не является стандартной функцией C, хотя, как мне кажется, она находится в MS C. Поскольку она не объявлена, компилятор C предполагает, что она возвращаетint
, что не подходит для аргументовstrcpy()
. А остальные проблемы, похоже, связаны с тем, что вы не используетеstrcmp()
для сравнения строк. Вам также нужно будет иметь дело с новой строкой, которуюfgets()
сохраняет во входных данных. - person Jonathan Leffler   schedule 22.02.2018strcmp
- person yano   schedule 22.02.2018ans == higher
- неправильный способ сравнения строк.ans
иhigher
- указатели на два разных массива. Эти указатели никогда не равны. Вы должны использоватьstrcmp(ans, higher)
. И в C нет стандартной функции для преобразования строки в верхний регистр. - person DYZ   schedule 22.02.2018rand()%6+1
rand ()% 6 дать значение в диапазоне [0,5] - person AndersK   schedule 22.02.2018