为什么我的txt文件无法在C ++中打开?

时间:2019-06-05 05:14:34

标签: c++

我正在尝试打开一个.txt文件,该文件包含0-9的整数值,每个数字在其行上直到最后一个数字为9。当我运行代码时,我正在使用im遇到打开问题我的txt文件。基于if and 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.

2 个答案:

答案 0 :(得分:1)

代码按预期工作,只需确保从文本文件所在的目录中执行编译的程序即可。

假设将源代码添加到名为main.cpp的文件中,并且在安装了gcc编译器的Linux或macOS上运行,则可以进行以下操作:

echo "Hello" > assignmentG1.txt
g++ main.cpp -o main
./main
Hello

答案 1 :(得分:0)

如果您的项目名称为project_name,则文件应位于正确的路径,因此请将文件保留在/project_name/project_name/assignmentG1.txt。 假设您正在使用Visual Studio。

相关问题