Search code examples
c++xcodeifstream

C++ ifstream XCode / VSCode


I'm a beginner in C++, I'm trying to open and read a file line by line, but it doesn't seem to work in XCode, while working in VSCode:

The code:

#include <iostream> // Imported to read
#include <fstream>  // Imported to read
#include <string>   // Imported to write lines
#include <vector>   // Imported to store lines
#include <cassert>  // Import to Test for IntList

using std::cout;
using std::endl;
using std::ifstream;
using std::string;
using std::vector;

int main(int argc, const char *argv[])
{
    /* ----------------------- READ INNPUT -----------------------*/
    cout << "----------------------- READ INPUT -----------------------" << endl;

    vector<string> lines; // to store the lines of the text file
    string line;          // <--- each new line to be read of the file

    ifstream file("input_text_file.txt"); // open the file

    int lineNumber = 1;
    if (file) // same as: if (myfile.good())
    {
        while (getline(file, line))
        {
            lines.push_back(line);
            cout << "line: " << lineNumber << " " << line << endl;
            lineNumber++;
        }
    }
    else
    {
        cout << "File not ok " << endl;
    }

    return 0;
}

in vscode:

(base) ➜  test git:(main) ✗ g++ test.cpp
(base) ➜  test git:(main) ✗ ./a.out
----------------------- READ INPUT -----------------------
line: 1 Do you like green eggs and ham?
line: 2 
line: 3 I do not like them, Sam-I-am.
line: 4 I do not like green eggs and ham!
line: 5 
line: 6 Would you like them here or there?
line: 7 
line: 8 I would not like them here or there.
line: 9 I would not like them anywhere.
line: 10 
line: 11 I do so like green eggs and ham!
line: 12 Thank you! Thank you,
line: 13 Sam-I-am!

while in XCode I have:

----------------------- READ INPUT -----------------------
File not ok 
Program ended with exit code: 0

My folder looks like this: the text file seems to be part of the XCode project

XCode Project Screenshot

The two files are also located in the same folder:

enter image description here

Do you have any idea of what might be causing this, and how to fix it ?


Solution

  • Your code assumes that input_text_file.txt is in the current working directory when the program is run. In Xcode, this is evidently not the case. The easiest fix is probably to use a fully qualified pathname, /path/to/your/file.