C ++如何处理文本文件(打开 - 写 - 闭合)

时间:2015-02-09 04:38:36

标签: c++

我正在开发一个显示菜单的程序,该菜单为用户提供了4个选项: 1.指定文件名(此步骤需要先执行)。 2.将数据写入该文件(例如名称和分数)。 3.显示文件的内容。 4.关闭文件。

所以我无法打开文件。到目前为止,我的代码工作正常,直到“用户输入验证”步骤(使用while循环)。但我仍然无法打开文件。

非常感谢任何帮助。

谢谢你,请原谅我可怜的英语。

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


int main()
{
    const int SPECIFY_NAME = 1,
        ADD_NAME_GAME_SCORE = 2,
        DISPLAY = 3,
        CLOSE_FILE = 4;

    //Variables:
    int choice;
    char end;

    string name;
    double gameScore;

    ifstream inputFile;
    string filename;

    //ofstream outputFile;

    do
    {
        //Display the menu:
        cout << "\n\t\tPlease choose your option from the menu below\n\n"
            << "1. Specify a file name\n"
            << "2. Add a name and game score to the file\n"
            << "3. Display the content of a file\n"
            << "4. Close the file\n\n"
            << "Enter your choice: ";
        cin >> choice;

        //Validate user input:
        while (choice < 1 || choice > 1)
        {
            if (choice > 0 && choice <= 4)
            {
                cout << "Please enter 1 to specify a file first: ";
                cin >> choice;
            }
            else
            {
                cout << "Please enter a valid menu choice: ";
                cin >> choice;
            }
        }

        switch (choice)
        {
        case 1:
            //Get the file name when user input 1:
            cout << "Type in the file name: ";
            cin >> filename;

            //Open the file:
            inputFile.open(filename);

            while (!inputFile)
            {
                cout << "Please check your file name and type it in correctly: ";
                cin >> filename;

                inputFile.open(filename);
            }

            cout << "Congratulation! You got the file open successfully.\n";
            break;

        case 2:
            cout << "Please type in your name: ";
            cin >> name;

            while (name.empty())
            {
                cout << "You did not type in your name.\n"
                    << "Please type again: ";
                cin >> name;
            }

            cout << "Please enter the game score: ";
            cin >> gameScore;

            while (gameScore < 0)
            {
                cout << "You have entered a negative number for game score.\n"
                    << "Please type in a possitive number: ";
                cin >> gameScore;
            }
        }

    }
    while (choice != 1);
    {
        cout << "press any key then ENTER to exit the program\n";
        cin >> end;
    }

    return 0;
}

0 个答案:

没有答案