这是我尝试运行的代码 -
#include <stdio.h>
int main()
{
char a;
int b;
printf("Name of Prisoner\n");
scanf("%c" ,a);
printf("How many years in jail as stated by the court?\n");
scanf("%d", b);
printf("Prisoner "a" goes to jail for "b" years\n"a,b);
return 0;
}
这是显示的错误 -
P.c: In function 'main':
P.c:14:23: error: expected ')' before 'a'
printf("Prisoner "a" goes to jail for "b" years\n"a,b);
^
如您所见,我在 C 或任何编程语言方面都处于非常初级的水平。我想收集囚犯的姓名和被判入狱的年数,然后简单地打印一份包含所收集数据的声明。但它没有被编译。给出了错误。 我很确定这是一个非常小且简单的解决方案,但我试图在课堂上跑一点,并且没有任何个人指导或老师与我同行。有人可以教育我这个问题吗?
您遇到的错误是由于
printf
函数中引号的使用不正确造成的。在 C 中,如果要将双引号包含在输出中,则需要对字符串内的双引号进行转义。此外,scanf
函数需要变量的地址来存储输入,因此您需要使用&a
和&b
而不是a
和b
。
这是更正后的代码:
#include <stdio.h>
int main()
{
char a;
int b;
printf("Name of Prisoner\n");
scanf(" %c", &a); // Use &a to store the character input
printf("How many years in jail as stated by the court?\n");
scanf("%d", &b); // Use &b to store the integer input
printf("Prisoner %c goes to jail for %d years\n", a, b); // Use %c and %d to print the character and integer
return 0;
}
这种代码的问题是,囚犯的名字只有一个字符。也许您希望它更长。这是重新审视的版本:
#include <stdio.h>
#define MAX_NAME_LEN 256
int main() {
char input_line[MAX_NAME_LEN];
char prisoner_name[MAX_NAME_LEN];
int years_in_jail;
printf("Name of Prisoner: ");
fgets(input_line, MAX_NAME_LEN, stdin); // Read the full line, including spaces
// Parse the input line to get the prisoner's name
sscanf(input_line, "%255s", prisoner_name); // Using %255s to avoid buffer overflow
printf("How many years in jail as stated by the court? ");
fgets(input_line, MAX_NAME_LEN, stdin); // Read the full line
// Parse the input line to get the number of years
sscanf(input_line, "%d", &years_in_jail);
printf("Prisoner %s goes to jail for %d years\n", prisoner_name, years_in_jail);
return 0;
}