读取文件形式仅显示最后输入的字符串,创建文件但为空

时间:2019-04-22 02:33:13

标签: c++

我的程序创建了一个文件,并在用户输入后对其命名,之后它将继续循环并询问您是否要继续添加到创建的文件中。在您说不之后,它将关闭文件并读取所创建文件的前三行。我的程序未将任何内容输出到文件中,它显示为空并且确实读取了三行,但它们是用户最后输入的行,但是是三行。如何解决这个问题?这是我的代码。

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>

using namespace std;

//Global Variables
fstream File;
string fileName, writeToFile;
char choice;

void write();
void read();
void exitprogram();

int main()
{
    // Name and open the output file
    cout << "What is the file name that you want to create?" << endl;
    cin >> fileName;

    cout << "File " << fileName << " has been created!" << endl;

    ofstream File(fileName.c_str());

    File.open(fileName.c_str());

    if (File.is_open())
    {
        cout << "File opened successfully." << endl;
        write();
    }

    else
    {
        cout << "Unable to open file" << endl;
    }

    return 0;
}

void write()
{
    choice = ' ';

    cout << "What do you want to add?: " << endl;
    getline(cin.ignore(),writeToFile);
    File << writeToFile << endl;

    cout << "Do you want to add something else to the file (1=YES or 2=NO): ";
    cin >> choice;

    switch(choice)
    {
        case '1' :
            write();
            break;
        case '2' :
            cout << "Saving..." << endl;
            File.close();
            read();
            break;
    }
}

void read()
{
    cout <<"Here are the first there lines of file " << fileName << endl;
    for (int counter = 1; counter <= 3; counter++)
    {
        File >> writeToFile;
        cout << writeToFile << endl;
    }
    exitprogram();
}

void exitprogram()
{
    exit(0);
}

1 个答案:

答案 0 :(得分:2)

通过在File中声明另一个write,可以遮盖 main使用的全局const displaySuma = () => document.getElementById("total").value = suma().toLocaleString( "es-ES" ); 。 (道德上不要使用全局变量,绝不要使用全局变量。相反,请传递参数,尽管您的大多数参数无论如何都可以设为局部变量。)