我目前在这段代码中得到标题错误。
void Option_3(char filename)
{ // profit for a month
FILE *ptr_file;
int num1, num2, num3;
int a[31],b[31],c[31];
int count=0;
int i;
ptr_file = fopen ( filename ,"r"); // error is here at file name
后主
void main()
{
int select;
char filename;
select = 0 ;
filename = "April.txt"; //here the equals sign is giving me the error.
您需要声明为char *
:
void main()
{
int select;
char *filename; // Note the declaration
select = 0 ;
filename = "April.txt";
在Option_3
的参数声明中也更改它:
void Option_3(char *filename)
原因是将其声明为char
意味着您有一个变量来保存char
类型的对象。C语言中的字符序列是以' '
结尾的字符数组,因此,char *
是正确的类型。
UPDATE:更合适的是将其声明为const char *
,因为您不能修改字符串文字
C语言中char
类型与char *
类型不兼容。很简单,因为它们是不同类型的组合。根据定义,char
保证是最小的类型(大小为1)。char *
与任何指针具有相同的大小:它必须足够大以容纳内存地址:通常在32位系统上为4,在64位系统上为8。
你将一个字符串常量赋值给一个声明为char
的变量,赋值期望右边的参数是这样的:
char foo = 'a';//single quotes indicate a char
或者,也许更多的是你想要的:
const char *foo = "April.txt";//double quotes indicative of char *
注意const
存储类:字符串常量不会被赋值给变量,而filename
的值将是字符串的内存地址,它存储在只读内存中。因此,它是const
:您不能更改它:
const char *foo = "foobar";
foo[0] = 'F';//<-- ERROR
要修改该值,可以这样写:
char foo[] = "foobar";
foo[0] = 'F';//Success!
这将创建一个足够大的数组,以容纳字符串,并复制字符。当然,如果var的值可能会改变,它也可能足够大,以容纳更大的字符串,在这种情况下:
char foo[100] = "up to 100 chars";
strcat(foo, "!!");
或者,使用动态内存(但如果可能的话要避免,因为堆更慢,需要更多的关注):
char *foo = malloc(20);//begin with 20 chars
if (foo == NULL)
exit( EXIT_FAILURE);//no memory could be allocated
strcpy(foo, "foobar");//copy string value into allocated memory
foo = realloc(foo, 50);//increase amount of allocated memory to hold 50
if (foo == NULL)//safety first:
exit(EXIT_FAILURE);
strncat(foo, "some huuuuuuge string", 30);//strncat for safety, again
啊,有很多方法可以做事情,这取决于你的具体需求