2014-03-05 28 views
-1

我是新來的C++編程,我無法存儲在文本文件中。它是一個非常簡單的程序。我之前使用相同的方法存儲了值,我得到的結果。無法使用fstream在文本文件中存儲值

#include<iostream> 
#include<fstream> 

using namespace std; 

int main() { 
    ofstream fout("one.txt",ios::in); 

    int val1, rel1; 
    char val2[20], rel2[20]; 

    cout<<" \n enter the integer value"; 
    cin>>val1; 
    cout<<" \n enter the string value "; 
    cin>>val2; 

    fout.close(); 

    ifstream fin("one.txt"); 

    fin>>rel1; 
    fin>>rel2; 

    cout<<"the integer value .\n"<<rel1; 
    cout<<"the string value .\n"<<rel2; 

    fin.close(); 

    if (fout==NULL) { 
    cout<<"the file is empty"; 
    } 

    return 0; 
} 

輸入名 荒誕輸出 整數值是32760 字符串值是00Dv0

+1

這是你的代碼看起來像在你的IDE /文本編輯器是什麼? –

+2

除了關閉它之外,你實際上不會用'fout'做任何事情。 –

+0

是@JosephMansfield完全相同 – user3383404

回答

0

有一個數這裏假設似乎需要澄清。

  • 如果你想寫入文件,你需要使用fout < < rel1;
  • 您(通常)無法像對待if(fout == NULL)那樣將對象與NULL進行比較。這適用於C#和Java,因爲在這些語言中,所有對象實際上都是引用,在C++中您可以指定何時需要對象以及何時需要引用。
  • 您指定要使用fout從文件讀取而不寫入「ios :: in」。

我有點無聊等待一些測試來完成,所以我寫了我會怎樣已經寫了程序:

#include<iostream> 
#include <string> 
#include<fstream> 

int main() { 
    std::ofstream fout("one.txt",std::ios::out); 

    int val1, rel1; 
    std::string val2, rel2; 

    std::cout <<"enter the integer value: "; 
    std::cin >>val1; 
    std::cout <<"enter the string value: "; 
    std::cin >>val2; 

    fout <<val1 <<" " <<val2; 
    fout.close(); 

    std::ifstream fin("one.txt", std::ios::in); 
    if(!fin.good()) { 
    std::cout <<"Failed to open file\n"; 
    return 1; 
    } 

    fin >>rel1; 
    fin >>rel2; 

    std::cout <<"the integer value: " <<rel1 <<"\n"; 
    std::cout <<"the string value: " <<rel2 <<"\n"; 

    fin.close(); 

    return 0; 
} 
+0

不太好的實施,謝謝它的工作,我想出了我的錯誤。 – user3383404

相關問題