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

标签 c++

我正在尝试打开一个包含整数值 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/

相关文章:

c++ - 基类指针只得到一个派生类变量值而不是基类变量值为什么?

c++ - vector 有问题吗?内存?

c++ - 仅当尝试在 Xcode 7.1 中使用 Instruments 时出现有关 Boost 文件的编译器错误

c++ - 二进制搜索树插入(递归)中的 Strcmp 错误?

c++ - 将具有无效字符的 Hex-CString 转换为 long?

c++ - Cuda:访问冲突写入位置 0x0000000000000000

c++ - 在 C++ 中从 PNG 中读取 RGB 值

c++ - 系统消息未处理异常

c++ - 为什么我们在 C++ 中使用 std::function 而不是原来的 C 函数指针?

c++ - 使用 CMake 检测支持的 C++ 标准