【问题标题】:C++ Trouble Reading a Text FileC++ 读取文本文件时遇到问题
【发布时间】:2012-10-22 18:53:37
【问题描述】:

我正在尝试读取文本文件,但没有任何输出。我觉得可能它在我的 Visual Studio 资源文件夹中没有正确链接,但如果我双击它 - 它在 Visual Studio 中打开正常,如果我测试它是否打开或者它是否很好,它不会遇到任何问题。该程序现在可以正常编译,但没有输出。没有任何内容打印到我的命令提示符。有什么建议吗?

代码

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main()
{
    char str[100];
    ifstream test;
    test.open("test.txt");

    while(test.getline(str, 100, '#'))
    {
        cout << str << endl;
    }

    test.close();
    return 0;
}

文本文件

This is a test Textfile#Read more lines here#and here

【问题讨论】:

  • 您知道文件是否可以正常打开吗?您应该检查返回值。
  • 我运行了一个 IF 语句来查看它是否为 is_open() 并且它进入了条件,所以我假设它打开了它(返回 1 / true)
  • 它只是在 linux 中测试了您的示例,一切都按预期工作。
  • 也许您只需要在 VS IDE 中的 return 0; 语句上放置一个断点即可查看一些输出,或者在 return 0; 之前添加类似 system("PAUSE");cin.get() 的内容。
  • @Agus 您是否通过 Visual Studio 对其进行了测试?我觉得这就是问题所在,除非我的问题是像下面的答案那样读入字符数组。

标签: c++ visual-studio-2010 text-files fstream


【解决方案1】:

您尝试按名称打开文件而不使用路径,这意味着该文件应位于您程序的当前工作目录中。

当您从 VS IDE 运行程序时,问题出在当前目录。 VS 默认将运行程序的当前工作目录设置为项目目录$(ProjectDir)。但是您的测试文件位于资源目​​录中。所以open() 函数找不到它,getline() 立即失败。

解决方案很简单 - 将您的测试文件复制到项目目录。或者将其复制到目标目录(创建程序.exe 文件的位置,通常为$(ProjectDir)\Debug$(ProjectDir)\Release)并在VS IDE 中更改工作目录设置:Project-&gt;Properties-&gt;Debugging-&gt;Working Directory,设置为$(TargetDir)。在这种情况下,它可以在 IDE 和命令行/Windows 资源管理器中运行。

另一种可能的解决方案 - 在您的 open() 调用中设置正确的文件路径。出于测试/教育目的,您可以对其进行硬编码,但实际上这不是一种好的软件开发方式。

【讨论】:

    【解决方案2】:

    不确定这是否会有所帮助,但我想简单地打开一个文本文件进行输出,然后将其读回。Visual Studio (2012) 似乎使这变得困难。我的解决方案如下所示:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    string getFilePath(const string& fileName) {
    	string path = __FILE__; //gets source code path, include file name
    	path = path.substr(0, 1 + path.find_last_of('\\')); //removes file name
    	path += fileName; //adds input file to path
    	path = "\\" + path;
    	return path;
    }
    
    void writeFile(const string& path) {
    	ofstream os{ path };
    	if (!os) cout << "file create error" << endl;
    	for (int i = 0; i < 15; ++i) {
    		os << i << endl;
    	}
    	os.close();
    }
    
    void readFile(const string& path) {
    	ifstream is{ path };
    	if (!is) cout << "file open error" << endl;
    	int val = -1;
    	while (is >> val) {
    		cout << val << endl;
    	}
    	is.close();
    }
    
    int main(int argc, char* argv[]) {
    	string path = getFilePath("file.txt");
    	cout << "Writing file..." << endl;
    	writeFile(path);
    	cout << "Reading file..." << endl;
    	readFile(path);
    	return 0;
    }

    【讨论】:

      猜你喜欢
      • 2012-09-28
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2017-09-01
      相关资源
      最近更新 更多