C++ ifstream XCode / VSCode

C++ ifstream XCode / VSCode

我是 C++ 的初学者,我尝试逐行打开和读取文件,但在 XCode 中似乎不起作用,而在 VSCode 中工作:

代码:

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

在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!

在 XCode 我有:

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

我的文件夹如下所示:文本文件似乎是 XCode 项目的一部分

这两个文件也位于同一个文件夹中:

您是否知道可能导致此问题的原因以及解决方法?

您的代码假定当程序为 运行 时 input_text_file.txt 位于当前工作目录中。在Xcode中,显然不是这样。最简单的修复可能是使用完全限定的路径名​​,/path/to/your/file.