我一直都在ifstream的问题在这里SO和我仍然有麻烦读一个简单的文本文件。我与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;
}

我已经证实的 input.txt中的文件是正确的“工作目录”通过检查argv[0]的价值。 Open方法只是将无法工作。

我也有麻烦debugging-应该我不能设置infile.good()infile.is_open()手表?我一直得到

Error: member function not present.

修改:更新的代码从.CPP文件全代码列表

<强>更新文件未在当前工作目录。这就是的项目文件的所在的目录。移动它有与在VS.NET调试时它工作。

有帮助吗?

解决方案

尝试指定所述打开模式时,使用按位或运算符。

infile.open ("input.txt", ios::ate | ios::in);

用于openmode 参数是一个位掩码。 ios::ate用于打开文件进行追加,并ios::in用于打开该文件用于读取输入。

如果你只是想读取的文件,你可能只需要使用:

infile.open ("input.txt", ios::in);

对于ifstream的默认打开方式是IOS ::中,这样你就可以摆脱那干脆现在。以下代码是使用克++为我工作。

#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;
}

其他提示

有时,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);

希望这有助于其他人一个快速的解决方案。我花了一段时间来找到这个设置自己。

我发现在你的代码的两个问题:

A)在语法错误 “IOS ::吃|| IOS ::在”=>应为 “IOS ::吃| IOS ::在”

B)“的ios ::吃”光标设置为文件的结尾 - 所以你什么也得不到,当你开始阅读

所以只要删除 “的ios ::吃” 和你的罚款:)

侨, 克里斯

infile.open ("input.txt", ios::ate || ios::in);

||是逻辑或操作,而不是位运算符(如比尔的Lizzard所述)。

所以我想你正在做等价于:

infile.open ("input.txt", true);

(假定既不IOS ::吃或IOS ::中是0)

尝试使用:

ifstream fStm("input.txt", ios::ate | ios::in);
  

我也有麻烦debugging-我不应该能够设置“infile.good()”或“infile.is_open()”的手表?我不断收到“错误:不存在的成员函数”

和适当的,包括:

#include <fstream> 

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top