当我将数据放入基于用户输入的“ myfile”命名的文件中时,当我在else语句中读取并显示该文件时,名称显示为“”,余额为0,文件数据为已删除。
我们fstream
昨天在我的C ++类中学习了它的命令。仍然是新手。老师说,使用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;
}
它应该从文件中读取数据并显示全名以及余额整数值。
计算机完全按照您的指示执行操作。
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句