读取变量名为C ++的文件

时间:2016-03-05 20:41:36

标签: c++ file-handling

我正在尝试为不同级别打开一个不同的文件,并且需要一个变量名来执行此操作。我尝试了以下但是给出了错误:“没有合适的从字符串到const char的转换”

void loadMap(){
    //string levelname;
    //levelname = '../Levels/Level' + level;
    FILE *file;
    file = fopen("../Levels/Level" + level + ".txt", "r"); //THIS LINE IS GIVING THE ERROR
    char section[80];
    int index = 0;
    int x = 0;
    int y = 0;

    while(true){
        fscanf(file, "%s", section);
        if(strcmp(section, "[Victor]") == 0){
            while(true){
                fscanf(file, "%d%d%d", &index, &x, &y);
                if(index == -1){
                    break;
                }
                victor.x = x;
                victor.y = y;
            }
        }

... ... //更多代码

3 个答案:

答案 0 :(得分:3)

首先,您应该使用std::ifstream,它是C ++方式(tm)。 其次,字符串的连接应该使用标题std::stringstream中的sstream来完成,这里是一个如何实现这一点的示例:

#include <iostream>
#include <sstream>
#include <fstream>

int main() {
    std::string level = "test";
    std::stringstream ss;
    ss<<"../Levels/Level"<<level<<".txt";

    std::ifstream file(ss.str());
    if(!file.is_open()) {
        // error
    } else {
        // continue
    }
}

答案 1 :(得分:2)

“../ Levels / Level”+ level +“。txt”被评估为字符串对象,但fopen()将const char *作为第一个参数。您可以通过以下方式修复它:

fopen(("../Levels/Level" + level + ".txt").c_str(), "r");

答案 2 :(得分:0)

FILE *file;
char buf[50];
snprintf(buf, sizeof(buf),"%s%d.txt","../Levels/Level",level);
file = fopen(buf, "r");
相关问题