【发布时间】:2016-08-29 08:16:35
【问题描述】:
(已解决)(我不知道如何关闭它)我正在尝试接受用户输入以打开源文件中的 .dat 文件,但我不知道为什么该文件一直无法打开.我已经检查了语法和其他东西,但我找不到解决方案。
#include <iostream>
#include <string>
#include <fstream>
#include "arrayFunctions.h"
using namespace std;
int main()
{
string fileName;
int size = 0;
ifstream inputFile;
do
{
cout << "Please enter file name: ";
getline(cin,fileName);
inputFile.open(fileName.c_str());
if (!inputFile)
{
cout << "The file \"" << fileName << "\" failed to open.\n"
<< "Check to see if the file exists and please try again"
<< endl << endl;
}
while (inputFile.good())
{
string stop = " ";
string num;
getline(inputFile, stop);
size++;
}
} while (!inputFile);
cout << size << endl << endl;
inputFile.close();
system("pause");
}
问题似乎在于实际打开文件,因为这失败了
do
{
ifstream inputFile("num.txt");
opened = true;
if (!inputFile.is_open())
{
cout << "The file \"" << fileName << "\" failed to open.\n"
<< "Check to see if the file exists and please try again"
<< endl << endl;
opened = false;
}
inputFile.close();
} while (!opened);
【问题讨论】:
-
你确定文件在它应该在的地方吗?例如,如果用户输入 foo.txt,则 foo.txt 文件必须位于进程的工作目录所在的任何位置
-
@Jerry Jerehmiah 显然我需要将文件移动到实际的源代码文件夹,而不是将其拖到 Microsoft Visual Studio 上的源代码文件夹。我选择你的作为答案,但它是一个评论
-
只需接受一个答案(如果正确)或写下您自己的答案并接受它