【问题标题】:How to convert a string to a ifstream如何将字符串转换为ifstream
【发布时间】:2011-02-02 23:36:00
【问题描述】:

我正在尝试使用 ifstream 打开一个文件,并且我想使用一个字符串作为路径(我的程序创建了一个字符串路径)。它会编译,但它保持空白。

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。

【问题讨论】:

    标签: c++ ifstream


    【解决方案1】:
    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);
    }
    

    【讨论】:

    • 这似乎不起作用,同样的事情发生了。我得到的只是一个空白的 myfile。
    • @bob:你这是什么意思?您正在使用 input 流,因此 myfile 必须已经包含您要读取的数据。
    • nurk,什么?我正在尝试使用 getline 从 txt 文件中输出所有文本。如果我之前设置了 ifstream 的名称,它工作正常,但我不能更改名称。
    【解决方案2】:

    你试过ifstream myfile(path.c_str());吗?

    查看previous postwhile (!whatever.eof()) 的问题。

    【讨论】:

    • !eof() 是一个长期存在的问题。 :(
    • @Fred Nurk:这是否意味着从现在开始它每年只会出现一次,而不是每周出现 3 次? :-)
    • 是的,我确实尝试过,这是我在发布之前所做的第二件事。
    【解决方案3】:

    我不确定这实际上是如何编译的,但我假设您正在寻找:

    #include <fstream>
    #include <string>
    //...
    //...
    std::string filename("somefile.txt");
    std::ifstream somefile(filename.c_str());
    if (somefile.is_open())
    {
        // do something
    }
    

    【讨论】:

    • 同样的问题 somefile 是空白的。
    【解决方案4】:
    //Check out piece of code working for me 
    //---------------------------------------
    char lBuffer[100];
    //---
    std::string myfile = "/var/log/mylog.log";
    std::ifstream log_file (myfile.str());
    //---
    log_file.getline(lBuffer,80);
    //---
    

    【讨论】:

      猜你喜欢
      • 2015-07-19
      • 2017-01-12
      • 2016-05-27
      • 2018-03-29
      • 1970-01-01
      • 2011-12-31
      • 2018-04-30
      相关资源
      最近更新 更多