【问题标题】:c++ invalid conversion from 'const char*' to 'char*'c++ 从 'const char*' 到 'char*' 的无效转换
【发布时间】:2017-10-14 17:34:07
【问题描述】:

我有这段代码:

void read_from_file(){
    ifstream fin;
    int index=-1;
    fin.open("eliza.dat");
    char line[MAX_RESP_LEN];
    while(fin){
        fin.getline(line,MAX_RESP_LEN);
        char *ptr = 0;
        ptr = strstr("@KWD@",line);
        if(strlen(line)<1){
            break;
        }
        else if(ptr!=NULL){
            // the next line is a keyword
            fin.getline(line,MAX_RESP_LEN);
            keys[++index].addword(line);
        }
        else{
            // it is a response
            keys[index].addresp(line);
        }    
    }
}

还有一个带有@KWD@ 标记的关键字的附加文件,但是当我编译此错误时:

error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive] ptr = strstr("@KWD@",line);

我有这些文件:

  • ostream
  • iostream
  • conio.h
  • unistd.h
  • 字符串
  • 时间.h
  • ctime
  • 数学.h
  • stdlib.h
  • 字符串
  • cstdlib
  • stdio.h
  • fstream.h

有什么遗漏吗?还是在此功能之前发生错误?代码有 400 行,所以我无法复制所有内容。

【问题讨论】:

  • 您将常量数据传递给strstr 并获得了指向常量数据的指针。能够修改它会导致问题。

标签: c++


【解决方案1】:
ptr = strstr("@KWD@",line);

改成

ptr = strstr(line,"@KWD@");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    相关资源
    最近更新 更多