gpt4 book ai didi

c++ - 从字符串常量到 'char*' 的折旧转换

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:42 25 4
gpt4 key购买 nike

我希望有人能帮助我。我正在将 C 语言程序转换为 C++,以便轻松使用字符串,但是当我去编译时,出现此错误:

inventory.cpp:225: warning: depreciated conversion from string constant to 'char*'

这是有问题的代码:

#define FNAME "database.dat"


// test data struct
struct t_Record
{
int number;
char word[100];
//String word[];
} Record;

int main (void)
{
int Rec = 0; // record number
FILE *File;

srand(time(NULL));

File = FileOpen(FNAME);
if (!File)
{
printf("Error hommie!\n\n");
exit(-1);
}

...etc.

这是编译器告诉我发生错误的地方:

File = FileOpen(FNAME); 

我只是看不出有什么问题...

编译器告诉我看的地方甚至没有与之关联的字符串或字符??

现在我明白这个错误以前见过,但我的问题是针对我的代码的。

最佳答案

问题是您正在尝试转换 string literal (类型为 const char[])到 char*

The place where the compiler tell me to look doesn't even have a string or char associated with it??

是的,它在文件的顶部:

#define FNAME "database.dat"

C++ 标准 n3337 § 2.14.5/1

字符串文字

A string literal is a sequence of characters (as defined in 2.14.3) surrounded by double quotes, optionally prefixed by R, u8, u8R, u, uR, U, UR, L, or LR, as in "...", R"(...)", u8"...", u8R"(...)", u"...", uR"* ̃(...)* ̃", U"...", UR"zzz(...)zzz", L"...", or LR"(...)", respectively.

您可以通过转换为 char* 来避免警告:

File = FileOpen( (char*)FNAME);

甚至更好地修改 FileOpen 以接受 const char*。这将更加安全和正确,因为您不打算修改字符串。

关于c++ - 从字符串常量到 'char*' 的折旧转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22723822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com