C++ 读取表单文件只显示最后输入的字符串,创建文件,但文件为空

C++ 读取表单文件只显示最后输入的字符串,创建文件,但文件为空,c++,C++,我的程序创建了一个文件,并在用户输入后将其命名,之后它将继续循环并询问是否要继续添加到创建的文件中。在您说“否”之后,它将关闭文件并读取创建的文件的前三行。我的程序没有向文件中输出任何内容,它看起来是空的,并且确实读取了三行,但它们是最后一个用户输入的行,但只读取了三次。如何解决这个问题?这是我的密码 #include <iostream> #include <fstream> #include <string> #include <stdlib.h&g

我的程序创建了一个文件,并在用户输入后将其命名,之后它将继续循环并询问是否要继续添加到创建的文件中。在您说“否”之后,它将关闭文件并读取创建的文件的前三行。我的程序没有向文件中输出任何内容,它看起来是空的,并且确实读取了三行,但它们是最后一个用户输入的行,但只读取了三次。如何解决这个问题?这是我的密码

#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);
}
#包括
#包括
#包括
#包括
使用名称空间std;
//全局变量
流文件;
字符串文件名,writeToFile;
字符选择;
无效写入();
无效读取();
void exitprogram();
int main()
{
//命名并打开输出文件
cout文件名;

通过在
main
中声明另一个
文件,可以隐藏
write
使用的全局
文件(寓意是永远不要使用全局变量。而是传递参数,尽管您的大多数文件都可以被设置为局部。)你通过在
main
中声明另一个来隐藏
write
所使用的全局
文件(寓意是绝不使用全局变量。相反,传递参数,尽管你的大多数参数都可以被设置为本地文件)。

流文件(fileName.c_str());File.open(fileName.c_str());
对于使用传递给构造函数的相同参数打开文件是多余的,因为该文件应该已经打开。
流文件(fileName.c_str());file.open(fileName.c_str());
如果在一个文件上打开与您传递给构造函数的参数相同的所有文件,这是多余的,因为该文件应该已经打开了。