2012-02-26 50 views
1

最近我做了一個簡單的C++程序,它使用Visual C++ 2010 express中的文件流write()和read()讀取和寫入類對象。該程序編譯得很好,但是當我進入.exe文件並打開它時,它會以快捷方式關閉。我在最後使用了'_getch()',但我仍然有這個問題。文件流程序沒有顯示.exe窗口

我有一個Turbo C++背景(怪我的學校)。

順便說一句,這是代碼。

#include "stdafx.h" 
#include "fstream" 
#include "iostream" 
#include "conio.h" 

using namespace std; 

struct Student 
{ 
    char name[40]; 
    char grade; 
    float marks; 
public: 
    void getdata(); 
    void display(); 
}; 

void Student :: getdata(void) 
{ 
    char ch; 
    cin.get(ch); 
    cout << "Enter name: "; 
    cin.getline(name, 40); 
    cout << "Enter grade: "; 
    cin >> grade; 
    cout << "Enter marks: "; 
    cin >> marks; 
} 

void Student :: display(void) 
{ 
    cout << "Name: " << name << endl; 
    cout << "Grade: " << grade << endl; 
    cout << "Marks: " << marks << endl; 
} 


int _tmain(int argc, _TCHAR* argv[]) 
{ 

    Student arts[3]; 
    fstream filin; 
    filin.open("Stu.dat", ios::in|ios::out); 
    if (!filin) 
    { 
     cout << "Cannot open file! \n"; 
     return 1; 
    } 
    cout << "Enter details for 3 students: "; 
    for (int i =0; i < 3; i++) 
    { 
     arts[i].getdata(); 
     filin.write((char *) & arts[i], sizeof (arts[i])); 
    } 
    filin.seekg(0); 
    cout << "The contents of stu.dat are shown below: "; 
    for(int i = 0; i < 3; i++) 
    { 
     filin.read((char *) & arts[i], sizeof (arts[i])); 
     arts[i].display(); 
    } 
    filin.close(); 
    _getch(); 
    return 0; 
} 
+0

查看輸出把之前的窗口關閉這個小功能的話:'無效doExit(){_getch(); }'並將'atexit(doExit);'添加到'main'函數的最頂端。或者,您可以從命令行運行程序而不是通過IDE來保持輸出顯示。 – spencercw 2012-02-26 11:26:41

回答

1

嘗試把一個_getch();這裏

cout << "Cannot open file! \n"; 
    _getch(); 
    return 1; 
+0

但它只在.exe窗口中顯示「無法打開文件!」。它不應該這樣做。 – 2012-02-26 11:36:50

+0

@Manav你應該很高興,你是錯誤報告的作品! – jrok 2012-02-26 12:28:31