Getline()不能打开文本文件

getline() not opening text file

本文关键字:文本 文件 不能 Getline      更新时间:2023-10-16

嗨,我目前在OSX上使用CodeBlocks 13.12。

我正在尝试打开下面的。txt文件


1号线第2行
第3行

我的代码是:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    cout<<'n';
    std::string line;
    ifstream myfile("textex.txt");
    if(myfile.is_open())
        cout << "File is open";
    else
        cout << "File not open";
    cout<<'n';
    return 0;
}

我已经将文件包含在项目文件夹中,并尝试链接它并编译它。

当我运行代码时,它显示"文件未打开",我不知道为什么?我是c++的新手,有人能解释一下为什么这不起作用吗?

可能是因为没有将项目文件夹设置为工作目录。

代替

    ifstream myfile("textex.txt");

    ifstream myfile;
    myfile.open("/Users/name/Code/textex.txt"); // Use the full path

尝试键入文件的完整路径,而不仅仅是文件名。告诉我接下来会发生什么。

另一个不相关的注意事项是,由于您使用的是"using namespace"指令,您也可以从string中省略std::,就像您使用cin和cout一样。这不是什么大问题,只是代码的外观。

当你从Code::Blocks中运行程序时,它运行在项目文件夹中,所以你的文本文件必须在你的项目文件夹中,否则文本文件必须在你的可执行文件所在的文件夹中。