【发布时间】:2026-02-10 21:25:05
【问题描述】:
我写了一个代码来制作“text1.txt”文件。它工作正常,然后我一直在尝试从文件中读取,但每次is_open() 函数都不会返回 true。即便如此,我还是按照它们在不同编译器中的完全相同的方式复制了其他代码,但它从来没有用过。我将如何解决这个问题:(
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file1("text1.txt");
string str;
if(file1.is_open()){
while(getline( file1, str)){
cout<<str;
}
}
else
cout<<"the file is not open"<<endl;
return 0;
}
【问题讨论】:
-
尝试完整的文件路径,例如
ifstream file1("/users/phidan/home/text1.txt"); -
欢迎来到 * Phidan,感谢您发布代码。下次尝试为您的问题提供更具描述性的标题,这将有助于其他有相同问题的用户更轻松地找到您的帖子。
标签: c++ file-handling file-read