1
#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!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

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;
}
Community
  • 1
  • 1
fnc12
  • 2,241
  • 1
  • 21
  • 27