C++ 使用变量访问文本文件

C++ 使用变量访问文本文件,c++,C++,有没有办法让我进去? 有一些文本文件,如john.txt micheal.txt james.txt 我可以使用以下代码访问它们: ifstream file1( "james.txt", ios::in ); 我可以像这样打开一个文件吗 string name = "james"; ifstream file1( name, ios::in ) 试试这个: char name[]="james.txt"; ifstream file1( name, ios::in ); 也许你可以尝试以

有没有办法让我进去? 有一些文本文件,如john.txt micheal.txt james.txt

我可以使用以下代码访问它们:

ifstream file1( "james.txt", ios::in );
我可以像这样打开一个文件吗

string name = "james"; ifstream file1( name, ios::in )
试试这个:

char name[]="james.txt";
ifstream file1( name, ios::in );

也许你可以尝试以下方式:

ifstream file1((name + ".txt").c_str(), ios::in);

在c++03及更早版本中,您需要使用
james.c_str()
,但原则上是这样的。(在C++11中,它可以正常工作。)[我假设您的意思是设置
string name=“james.txt”
。否则
.txt
将丢失。]“也许您可以试试”是什么意思?我说“也许你可以试试”,因为这个问题不是很清楚,我不确定答案是否正确。我很高兴它做到了。