我是C ++的新手。
我试图使用fstream
读取文件。
这是代码,
我把文件放在a.out目录下但仍然无法读取,我的错误在哪里?
#include<iostream>
#include<fstream>
int main()
{
std::ifstream myfile("my.txt");
int a, b;
while(myfile>>a>>b)
std::cout<<a<<b;
return 0;
}
答案 0 :(得分:2)
尝试:
#include <iostream>
#include <fstream>
#include <unistd.h>
int main()
{
char* name = get_current_dir_name();
std::cout << "Current Working Dir: " << name << "\n";
free(name);
std::ifstream myfile("my.txt");
if (!myfile))
{
std::cout << "Failed to open file\n";
exit(1);
}
int a, b;
while(myfile>>a>>b)
{
std::cout<<a<<b;
}
return 0;
}
答案 1 :(得分:1)
确保该文件位于.exe
的当前目录中。这通常与.exe
位于硬盘上的目录相同。
如果您不知道当前目录是什么,我建议您使用完整路径。