输入adn中的问题从文件中读取数据 [英] Problem In Entering adn Reading The Dat From File

查看:105
本文介绍了输入adn中的问题从文件中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Everyone!



i我正在尝试用C ++编写文件处理程序,但是我从File.My程序中获取输入错误我正确,但是到了查看程序的时候没有向我显示任何内容并且停止执行该程序。



请参阅下面的程序并告诉我什么是显示程序的一部分或程序中的任何位置时出错。

Hello Everyone!

i am trying to make File handling program in C++,but i got the Error on Displaying the Records From the File.My Program take input from me Correctly but when the time is to View Program did not show me anything and Stop all Execution of the Program.

Please see the Below Program and tell me what is the Error in Displaying Part of The Program or Anywhere in the Program.

#include <iostream>
#include <fstream>
using namespace std;

struct Student
{
private:
    string Name;
    int Age;
public:
    Student()
    {
        Name="";
        Age=0;
    }
    void GetData()
    {
        cout<<"Enter Name:";
        cin>>Name;
        cout<<"\nEnter Age:";
        cin>>Age;
    }
    void ShowData()
    {
        cout<<"Name:"<<Name;
        cout<<"\nAge:"<<Age;
    }
};
void Write_File()
{
    Student Obj;
    ofstream Input_Data;
    Input_Data.open("Student_Data.dat",ios::app|ios::binary);
    Obj.GetData();
    Input_Data.write(reinterpret_cast<char*> (&Obj),sizeof(Student));
    Input_Data.close();
}
void Display_Data()
{
    Student Obj;
    ifstream Output_Data;
    Output_Data.open("Student_Data.dat",ios::binary);
    while(Output_Data.read(reinterpret_cast<char*> (&Obj),sizeof(Student)))
    {
        Obj.ShowData();
    }
    Output_Data.close();
}
int main()
{
    Student Obj;
    char Choice;
    cout<<"Write Data Into The File."<<endl<<endl;
    do
    {
        Write_File();
        cout<<"\n\t\t\tDo You Want To Enter More Data Y/N :";
        cin>>Choice;
   }while(Choice=='y' || Choice=='Y');
    cout<<"\n\nOutput Of The Record:"<<endl;
    Display_Data();
    return 0;
}

推荐答案

你有一个范围问题。



你在main()中声明Student Obj但从不使用它。



替换...



You have a scope problem.

You declare "Student Obj" in main() but never use it.

Replace ...

void Write_File()
{
    Student Obj;





...含...





... with ...

void Write_File(Student &Obj)
{





对Display_Data执行相同操作。将主要功能更改为以下内容:





Do the same for Display_Data. Change you main function to something like this:

int main()
{
    Student Obj;
    char Choice;

    cout << "Write Data Into The File." << endl << endl;
    do
    {
        Write_File(Obj);
        cout << "\n\t\t\tDo You Want To Enter More Data Y/N :";
        cin >> Choice;
    }
    while(Choice=='y' || Choice=='Y');
    cout << "\n\nOutput Of The Record:" << endl;
    Display_Data(Obj);
    return 0;
}


这篇关于输入adn中的问题从文件中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆