我正在尝试打开一个包含整数值 0-9 的 .txt 文件,每个单独的数字在其自己的行上,直到最后一个数字为 9。当我运行我正在使用的代码时,我遇到了打开问题我的 txt 文件。基于 if 和 else 语句提供了它无法打开导致此问题的原因以及我可以使用什么方法打开我的记事本 .txt 文件。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream infile; //Container for the file
infile.open("assignmentG1.txt"); //Name of the file you want to open
string stringFromFile; //string variables to store extracted strings
if(infile.fail()) {//Display error if the file failed to open
cout<<"Input file failed to open";
}
else
{
getline(infile, stringFromFile);
}
cout<<stringFromFile;
}
input file failed to open.
最佳答案
代码按预期运行,只需确保从文本文件所在的目录执行编译后的程序。
假设将源代码添加到名为 main.cpp
的文件中,并在安装了 gcc 编译器的 Linux 或 macOS 上运行,则以下工作:
echo "Hello" > assignmentG1.txt
g++ main.cpp -o main
./main
Hello
关于c++ - 为什么我的 txt 文件无法在 C++ 中打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56454570/