我正在尝试读取文本文件,但没有任何内容.我觉得它可能没有在我的 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++ 无法读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
为什么两个函数的地址相同?Why do two functions have the same address?(为什么两个函数的地址相同?)
为什么 std::function 的初始化程序必须是可复制构Why the initializer of std::function has to be CopyConstructible?(为什么 std::function 的初始化程序必须是可复制构造的?)
混合模板与多态性mixing templates with polymorphism(混合模板与多态性)
我什么时候应该使用关键字“typename"?使用模When should I use the keyword quot;typenamequot; when using templates(我什么时候应该使用关键字“typename?使用模板时)
依赖名称解析命名空间 std/标准库Dependent name resolution amp; namespace std / Standard Library(依赖名称解析命名空间 std/标准库)
gcc 可以编译可变参数模板,而 clang 不能gcc can compile a variadic template while clang cannot(gcc 可以编译可变参数模板,而 clang 不能)