用户输入和读取文件内容

时间:2014-04-11 14:30:18

标签: c++ fstream ifstream

对于完全公开,这是我的编程课程的作业,我只是想要一些代码的提示或建议。

分配详细信息仅供参考。

编写一个程序,该程序将从用户读取数字1-100,以及数据文件的名称,并告诉用户文件中的单词以及数字在数据文件中显示的次数。验证输入编号(保持询问直到有效)并验证文件是否已成功打开。

文本文件内容:亲爱的10 20 21 19 20


#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>  // Needed for exit()
using namespace std;

int main()
{
    ifstream inputFile;
    string fileName;
    int value;

    cout << "Enter the file name: ";
    getline(cin, fileName);

    // Open the file
    inputFile.open(fileName.c_str());

    // Check for successful opening
    if(inputFile.fail())
    {
       cerr << "Error Opening File" << endl;
       exit(1);
    }

    cout << "\nThe file has been successfully opened for reading.\n";

    cout << "Pick a number between 1 through 100. ";
    cin >> value;

    if (value >= 1 && value <= 100)
    {
     cout << value << " is in the acceptable range.\n";
    }
    else
    {
     cout << "Please enter a number from 1 to 100. ";
     cin >> value;
    }

    string word;
    int number;
    int count = 0;

    infile >> number;

    // Read a file until you've reached the end
    while (!inputFile.eof())
    {
        if (number == x)
        {
            sum1++
        }
        infile >> number;
    }
    cout << sum1;

    while (!inputFile.eof())
    {
       inputFile >> word;
        if (word == "input")
        {
            count++;
        }
    }

    // Close the file
    inputFile.close();
    return 0;
}

任何提示或建议都会受到高度赞赏,因为我现在失去了这项任务的fstream部分。

提前致谢,

詹姆斯

0 个答案:

没有答案