【发布时间】:2016-07-01 04:27:38
【问题描述】:
大家晚上好。 我应该首先说我对编程和 C++ 语言完全陌生。
我在打开文件以在我的程序中使用它时遇到问题。我已经阅读了类似的帖子并遵循了建议。我正在使用 ifstream 来声明我的输入文件并包含我要打开的文件的完整路径。我尝试将文件移动到其他文件夹,包括工作区文件中,我尝试只用标题打开它,我在声明我的输入文件后包含了命令“ios::in”;无论我做了什么更改,我都会收到我创建的相同错误消息:
打开失败。
我已经尝试了 3 种不同的编译器,目前使用 CodeRunner。我确实将初始消息打印到输出文件中:
此程序读取并计算输入文件中单词的统计信息 并创建一个包含结果的输出文件。 它将计算单词的总数,不同数量的单词数量 字母数量和每个单词的平均字母数量。
我的变量声明中是否缺少某些内容? 我错过了任何指令吗? 它是我用来打开它的命令吗? 感谢您的宝贵时间,如果您有任何想法或解决方案,我们将不胜感激。
// Directives
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <fstream>
#include <string>
using namespace std;
void words_statistics(ifstream & fin, ofstream & fout);
// Opens a file, reads it, computes statistics of for the words on the file.
int main (){
// Variables declaration
ifstream fin; //Variable type for Input files.
ofstream fout; // Variable type for output files.
string inFile, outFile;
fout << "This program reads and computes the statistics for the words on a input file \n";
fout << "and creates an output file with the results.\n";
fout << "It will compute the total number of words, amount of words with different number \n";
fout << "of letters and the average quantity of letters per word.\n";
// Open input file to read-in
fin.open("/Macintosh HD/Users/antonydelacruz/Downloads/words.txt");
if(fin.fail()) // Generate Error message input file.
{
cout << inFile << " Failed to open."<< endl;
exit (1);
}
fout.open("/Macintosh HD/Users/antonydelacruz/Downloads/words_statistics.txt");
if(fout.fail()) // Error message in case that the program can't access output file.
{
cout << inFile << " Failed to open file Words Statistics."<< endl;
exit (1);
}
// Function call
words_statistics(fin, fout);
fin.close(); // Close input File.
fout.close(); // Close output file.
return 0;
}
// Function Definition
void words_statistics(ifstream & fin, ofstream & fout)
{
// Variable Declaration
std::string inFile, outFile;
int lettersQuantity=0; //Variable to accumulate the amount of letters per word.
int totalWords=0; // Variable to accumulate the total amount of Words.
double avg=0;
int un, deux, trois, quatre, cinq, six, sept, huit, neuf, dix, onze, douze, treize, otre; // Variables to accummulate words depending on the amount of letters that they have.
un = deux = trois = quatre = cinq = six = sept = huit = neuf = dix = onze = douze = treize = otre=0;
while (!fin.eof()) { //Specifies to noly use the switch feature while there is data to read.
(fin >> inFile); // Extracts data from file.
lettersQuantity++; // Adds the amount of letters per word.
totalWords++; // Adds the total amount of words
switch (lettersQuantity){ //Evaluates each word and adds it to a category depending on how many letters the word has.
【问题讨论】: