如何将字符串转换为 ifstream

发布于 2024-10-15 14:38:10 字数 512 浏览 4 评论 0原文

我正在尝试使用 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。

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;
   }
}

I am using windows 7, My compiler is VC++ 2010.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

自控 2024-10-22 14:38:10
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);
}
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);
}
三生路 2024-10-22 14:38:10

您是否尝试过ifstream myfile(path.c_str());

请参阅关于 while (!不管怎样。eof())

Have you tried ifstream myfile(path.c_str());?

See a previous post about the problems with while (!whatever.eof()).

预谋 2024-10-22 14:38:10

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

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

I'm unsure as to how this actually compiles, but I assume you are looking for:

#include <fstream>
#include <string>
//...
//...
std::string filename("somefile.txt");
std::ifstream somefile(filename.c_str());
if (somefile.is_open())
{
    // do something
}
裂开嘴轻声笑有多痛 2024-10-22 14:38:10
//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);
//---
//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);
//---
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文