需要帮助的使用infile.open使用变量和字符串组合打开一个文件(),在C打开文件++使用可变
ifstream infile;
infile.open("data_x.txt");
我需要这样的事,但在data_X.txt的X必须是一个可以改变的变量。
需要帮助的使用infile.open使用变量和字符串组合打开一个文件(),在C打开文件++使用可变
ifstream infile;
infile.open("data_x.txt");
我需要这样的事,但在data_X.txt的X必须是一个可以改变的变量。
与C++,如果我理解正确你的问题,你可以使用一个字符串流
std::ostringstream file_name;
file_name << "data_" << somevar;
infile.open(file_name.str());
我不知道。你需要打开一个名为“something_X.txt”的文件,但有可能用某些变量的值替换“X”?如果是这样的:
template <typename T>
ifstream read_file(const char* baseName, const T& value, const char* extension)
{
std::ostringstream file_path; // Here we will assemble our name
file_path<<baseName<<value<<extension; // Add baseName, value and extension.
ifstream file_handle(file_path.str()); // Open the file.
if(!file_handle)
{
//This file doesn't exist! Notify user in some way.
}
return file_handle; // Return handle to file we have opened.
}
现在你可以这样做:
file_1 = read_file("data_", 5, ".txt"); //Opens "data_5.txt"
file_2 = read_file("personal", "info", ".ini"); //Opens "personalinfo.ini"
我提供了一个更通用的解决方案,让您可以自定义(在特定情况下“data_中”)的名字定前缀和扩展文件。例如:此循环将打开“texture_1.jpg”,“texture_2.jpg”,...,“texture_10.jpg”。
const char* base_name = "texture_";
const char* extension = ".png";
for(int i = 1; i <= 10; ++i)
{
ifstream tex_file = read_file(base_name , i, extension);
//read data from this file
tex_file.close();
}
由于功能模板,你可以使用任何类型T的变量,其中有一个有效的运营商< <(ostringstream &,常量牛逼&) - 所有内置类型都满足这一要求。去这里了解详情:cplusplus.com: operator<<。
你是第二个用法的例子是错误的,它打开“personalinfo.ini”,该函数不会添加下划线.. –
'你是第二个用法的例子是错误的' - >它不是。这是完全有效的代码,如果存在,将会打开文件。如果有什么不对,那就是评论。这是我们通常所说的'打字错误'。固定。 –
我的错误,评论中有一个错字。 8-) –
http://en.cppreference.com/w/cpp/string/basic_string/to_string – chris