Dav*_*sky 7 c++ ifstream visual-studio
我已经在这里讨论了ifstream问题,而且我仍然无法阅读简单的文本文件.我正在使用Visual Studio 2008.
这是我的代码:
// CPPFileIO.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
infile.open("input.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
_getch();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我通过检查值来确认input.txt文件在正确的"工作目录"中argv[0].Open方法不起作用.
我也无法调试 - 如果我无法设置手表infile.good()或infile.is_open()?我一直在
Error: member function not present.
Run Code Online (Sandbox Code Playgroud)
编辑:使用.CPP文件的完整代码更新了代码清单.
更新:该文件不在当前工作目录中.这是项目文件所在的目录.移动到那里,它在VS.NET中调试时有效.
指定打开模式时,请尝试使用按位OR运算符.
infile.open ("input.txt", ios::ate | ios::in);
Run Code Online (Sandbox Code Playgroud)
该用于openmode参数是一个位掩码. ios::ate用于打开文件以进行追加,ios::in用于打开文件以读取输入.
如果您只想阅读该文件,您可以使用:
infile.open ("input.txt", ios::in);
Run Code Online (Sandbox Code Playgroud)
ifstream的默认打开模式是ios :: in,所以你现在可以完全摆脱它.以下代码使用g ++为我工作.
#include <iostream>
#include <fstream>
#include <cstdio>
using namespace std;
int main(int argc, char** argv) {
ifstream infile;
infile.open ("input.txt");
if (infile)
{
while (infile.good())
cout << (char) infile.get();
}
else
{
cout << "Unable to open file.";
}
infile.close();
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
有时Visual Studio会将您的exe文件从源代码中删除.默认情况下,VS可能只查找从exe文件开始的文件.此过程是一个简单的步骤,用于从与源代码相同的目录中获取输入txt文件.您是否不想修复IDE设置?
using namespace std;
ifstream infile;
string path = __FILE__; //gets source code path, include file name
path = path.substr(0,1+path.find_last_of('\\')); //removes file name
path+= "input.txt"; //adds input file to path
infile.open(path);
Run Code Online (Sandbox Code Playgroud)
希望这有助于其他人快速解决问题.我花了一段时间才找到这个设置.
| 归档时间: |
|
| 查看次数: |
20485 次 |
| 最近记录: |