在C ++中使用Visual Studio读取文本文件时遇到问题 [英] Trouble Reading a Text File with Visual Studio in C++
问题描述
我无法让Visual Studio读取文本文件.下面是我的代码.该文件可以在Unix环境中完美打开,但是将其复制并粘贴到Visual Studio后将无法正常工作.我正在使用fstream打开文件.为什么不读取文件?
I can not get Visual Studio to read in a text file. Below is the code I have. The file opens perfectly in a Unix Environment, but it does not work when copied and pasted into Visual Studio. I am using fstream to open the file. Why the file is not being read?
当我运行程序时,它会生成,但没有输出.我有一条输出语句 cout<<"inf \ n"
.因此,甚至没有达到循环,这就是为什么我认为没有读取文件的原因.同样,当我在Unix环境中运行相同的代码时,输出语句的确会显示,并显示文件中的值(通过tree.insert(),tree.remove()).
When I run the program, it builds but I get no output. I have an output statement cout << "inf\n"
. So the loop is not even being reached, which is why I believe the file is not being read. Again, when I run the same code in a Unix environment the output statement does display and the values from the file are displayed ( via tree.insert(), tree.remove() ).
我在此链接中尝试了该解决方案.如它的建议,我将工作目录更改为$(ProjectDir)\ Debug和$(ProjectDir)\ Release.另外,我将文本文件从资源"文件夹移动到了解决方案资源管理器中的源"文件夹.但是,该文件仍未被读取.
I tried the solution in this link. As it suggested, I changed my working directory to $(ProjectDir)\Debug and $(ProjectDir)\Release. Also, I moved my text file from the Resources folder to my Source Folder in the Solution Explorer. However, the file still was not being read.
我还更新了代码,以包含 cerr<<错误:"<<strerror(errno);
直接在fstream inf("BTREE5_1.txt")之后.使用此行代码,我得到的输出是
I also updated my code to include cerr << "Error: " << strerror(errno);
directly after fstream inf ("BTREE5_1.txt"). With this line of code the output I get is
错误:没有这样的文件或目录
有人可以解释为什么吗?如上所述,我的文本文件与我的代码位于同一文件夹中.
Can someone please explain why? My text files are in the same folder as my code as explained above.
#define _CRT_SECURE_NO_WARNINGS
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include "BTree.h"
using namespace std;
int main()
{
bool first = true;
BTree tree(6, 2);
int value;
char s[80], command;
ifstream inf("BTree5_1.txt");
cerr << "Error: " << strerror(errno);
inf.getline(s, 80);
while (inf >> command >> value)
{
cout << "inf\n";
if (command == 'i')
tree.insert(value);
else
{
if (first)
{
cout << "After all insertions.\n";
tree.print();
first = false;
} // if first
cout << "Deleting " << value << ". \n";
tree.remove(value);
tree.print();
// fgets(s, 80, stdin);
} // else deletion
} // while
system("PAUSE");
return 0;
} // main
推荐答案
问题是我从Unix环境复制并粘贴了文本文件.为了解决这个问题,我只是将文本文件从C盘放入目录中.
The problem was that I copied and pasted my text files from the Unix Environment. To fix this I just placed the text files into my Directory from my C Drive.
ie>)C:\ Users \ s.proctor \ Documents \ Visual Studio 2015 \ Projects \ ecs60 \ p2 \ p2 \ p2
ie>) C:\Users\s.proctor\Documents\Visual Studio 2015\Projects\ecs60\p2\p2\p2
这篇关于在C ++中使用Visual Studio读取文本文件时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!