C ++读取文本文件时遇到问题 [英] C++ Trouble Reading a Text File

查看:80
本文介绍了C ++读取文本文件时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取文本文件,但是没有任何声音.我觉得也许它在我的Visual Studio Resources文件夹中未正确链接,但是如果我双击它-它在Visual Studio中可以很好地打开,并且如果我测试看看它是否打开还是很好的话,也不会出现任何问题.该程序现在可以正常编译,但是没有输出.什么都不会打印到我的命令提示符下.有什么建议吗?

I'm trying to read a text file but nothing is coming out. I feel like maybe It's not linking correctly in my Visual Studio Resources folder but if I double click it - it opens fine in visual studio and it doesn't run into any problems if I test to see if it opens or if it is good. The program compiles fine right now but there's not output. Nothing prints to my command prompt. Any suggestions?

代码

#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

推荐答案

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

You try to open file by name without path, this means the file shall be in current working directory of your program.

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

The problem is with current directory when you run your program from VS IDE. VS by default sets current working directory for runnning program to project directory $(ProjectDir). But your test file resides in resources directory. So open() function could not find it and getline() immediately fails.

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

Solution is simple - copy your test file to project directory. Or copy it to target directory (where your program .exe file is created, typically $(ProjectDir)\Debug or $(ProjectDir)\Release) and change working directory setting in VS IDE: Project->Properties->Debugging->Working Directory, set to $(TargetDir). In this case it will work both from IDE and command line/Windows Explorer.

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

Another possible solution - set correct path to file in your open() call. For testing/education purposes you could hardcode it, but actually this is not good style of software development.

这篇关于C ++读取文本文件时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆