繁体   English   中英

我的代码不会使用 ifstream 和 ofstream 从文件中读取和显示数据

[英]My code will not read and display data from a file using ifstream and ofstream

虽然我的数据是根据用户输入的“myfile”放入文件命名的,当我go读取并在else语句中显示时,名称显示为“”,余额为0,文件数据为删除。

我们昨天刚刚在我的 C++ class 中学习了fstream及其命令。 使用它还是新手。 老师说用getline(inputfile, name)inputfile >> balance应该读取数据。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{

string myfile;
int balance = 0;
string name;

cout << "Enter your first name." << endl;
getline (cin, myfile);

ifstream inputfile(myfile);
ofstream outputfile(myfile);

if ( ! inputfile.good() )
{
        cout << "Enter your FIRST and LAST name." << endl;
        getline(cin, name);
        outputfile << name << endl;
        cout << "Hello " << name << endl;

        cout << "Enter your initial balance." << endl;
        cin >> balance;
        outputfile << balance << endl;
}
else
{
        getline(inputfile, name);
        cout << "Welcome Back" << name << endl;
        cout << "Here is a log of all your BALANCE activity." << endl;

       inputfile >> balance;
       cout << "Your balance is " << balance << endl;
}

outputfile.close();
inputfile.close();

return 0;
}

它应该从文件中读取数据并显示全名以及余额 integer 值。

计算机正在按照您告诉它的方式进行操作。

getline (cin, myfile);

从用户那里获取一些文本并将其存储在myFile中。

ifstream inputfile(myfile);

打开以myFile命名的文件进行读取(如果存在)。

ofstream outputfile(myfile);

打开您刚刚打开的同一个文件,但这次是为了写入。 如果文件存在,则销毁其内容。 如果该文件不存在,请创建它。

然后继续执行if语句。 如果文件已经存在,则继续执行else子句。 在那里您发现文件的内容已被破坏。 不足为奇,因为这是ofstream打开现有文件时的默认行为。

您可能想要做的是将outputfile的声明移动到if语句中,以便仅在文件不存在时才命中它。

if ( ! inputfile.good() )
{
        ofstream outputfile(myfile);

        cout << "Enter your FIRST and LAST name." << endl;
        getline(cin, name);
        outputfile << name << endl;
        cout << "Hello " << name << endl;

        cout << "Enter your initial balance." << endl;
        cin >> balance;
        outputfile << balance << endl;
        // No need to explicitly close the file, as the destructor will handle that.
}
else
{
    // etc.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM