简体   繁体   中英

How to Ifstream codeblocks on mac?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream inFile;
    inFile.open("test.txt");

    int foo;
    string sFoo;

    inFile >> sFoo;
    inFile >> foo;

    cout << "the name is " << sFoo << endl;
    cout << "the first number is "  << foo << endl;

    inFile >> foo;
    cout << "the second number is " << foo << endl;

    cout << "Hello World!";
    return 0;
}

I have tried putting my text file in the same folder. However, for some reason it is not able to read the text file. Please can someone tell me what to do in codeblocks on macbook to make this happen!

You have to write full absolute path of your file and not relative. I've answered the same question here .

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream inFile;
    inFile.open("/Users/user/Desktop/test.txt");
    if(inFile){
        int foo;

        string sFoo;

        inFile >> sFoo;
        inFile >> foo;

        cout << "the name is " << sFoo << endl;
        cout << "the first number is "  << foo << endl;

        inFile >> foo;
        cout << "the second number is " << foo << endl;

        cout << "Hello World!"; 
        inFile.close();

    }else{
        cout<<"unable to open file"<<endl;
    }
    return 0;
}

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