如何在Mac上ifstream CodeBlocks

How to Ifstream codeblocks on mac?

本文关键字:ifstream CodeBlocks Mac      更新时间:2023-10-16
#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;
}

我尝试将文本文件放在同一文件夹中。但是,由于某种原因,它无法读取文本文件。请有人告诉我在MacBook上的CodeBlocks中该怎么做!

您必须编写文件的完整绝对路径,而不是相对。我在这里回答了同样的问题。

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