如何将字符串转换为ifstream [英] How to convert a string to a ifstream
本文介绍了如何将字符串转换为ifstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图打开一个文件与ifstream和我想使用一个字符串作为路径(我的程序使一个字符串路径)。它将编译,但它保持空白。
i am trying to open a file with ifstream and i want to use a string as the path (my program makes a string path). it will compile but it stays blank.
string path = NameOfTheFile; // it would be something close to "c:\file\textfile.txt"
string line;
ifstream myfile (path); // will compile but wont do anything.
// ifstream myfile ("c:\\file\\textfile.txt"); // This works but i can't change it
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
}
我使用windows 7,我的编译器是VC ++ 2010 。
I am using windows 7, My compiler is VC++ 2010.
推荐答案
string path = compute_file_path();
ifstream myfile (path.c_str());
if (!myfile) {
// open failed, handle that
}
else for (string line; getline(myfile, line);) {
use(line);
}
这篇关于如何将字符串转换为ifstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文