简体   繁体   中英

getline() not opening text file

Hi I am currently using CodeBlocks 13.12 on OSX.

I am trying to open the following .txt file

line 1
line 2
line 3

My code is just:

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

I have also included the file in the project folder and have tried linking it and compiling it.

When I run the code, it displays"File not open" and I'm not sure why? I'm new to c++, can someone please explain why this isn't working?

Possibly because the project folder is not set as the working directory. Try specifying the full path.

Try typing the full path of the file instead of just the file name. Tell me what happens then.

On another note but unrelated, since you are using the "using namespace" directive, you may as well omit std:: from string just like you did with cin and cout. It is not a big deal, just the look of the code.

Instead of

    ifstream myfile("textex.txt");

Try

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

当您从Code :: Blocks运行程序时,该程序将在项目文件夹中运行,因此文本文件必须位于项目文件夹中,否则文本文件必须位于可执行文件所在的文件夹中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM