2011-04-13 62 views
1

如何從輸入文件中獲取數字以用於輸出文件?如何在C++中將數字讀入輸出文件

例如,說我想讀在INFILE號碼,並使用這些數字顯示爲上OUTFILE學生證。

+0

這個功課? – 2011-04-13 16:39:13

+0

如果這是作業,請將其標記爲如此。 – DanTheMan 2011-04-13 16:39:24

+1

這基本上是關係到其他問題,他只是問http://stackoverflow.com/questions/5652295/how-do-i-do-this-c-program – 2011-04-13 16:40:02

回答

0

這取決於你如何編寫值。

顯然,你需要打開該文件。
如果沃特與outfile << data數據,你可能會與infile >> data閱讀。

如果您使用fprintf(),您可能會用fscanf()來讀取它,但不一定。

要開始了,你怎麼樣向我們展示你沒有寫outfile中,並MAVE快速嘗試你會如何閱讀並告訴我們什麼。那麼我們可以給你一些關於如何進行的指導。

祝你好運!

更新
你看起來相當丟失。我寫了一個簡短的程序來完成你需要的一些功能,但是我沒有包含任何註釋,所以你需要閱讀代碼。看看你是否可以弄清楚你需要什麼。

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


bool WriteNums(const std::string &sFileName, int nVal, double dVal) 
{ 
    std::ofstream ofstr(sFileName); 
    if (!ofstr.is_open()) 
    { 
     std::cerr << "Open output file failed\n"; 
     return false; 
    } 
    ofstr << nVal << " " << dVal; 
    if (ofstr.fail()) 
    { 
     std::cerr << "Write to file failed\n"; 
     return false; 
    } 
    return true; 
} 

bool ReadNums(const std::string &sFileName, int &nVal, double &dVal) 
{ 
    std::ifstream ifstr(sFileName); 
    if (!ifstr.is_open()) 
    { 
     std::cerr << "Open input file failed\n"; 
     return false; 
    } 
    ifstr >> nVal >> dVal; 
    if (ifstr.fail()) 
    { 
     std::cerr << "Read from file failed\n"; 
     return false; 
    } 
    return true; 
} 

int main() 
{ 
    const std::string sFileName("MyStyff.txt"); 
    if(WriteNums(sFileName, 42, 1.23456)) 
    { 
     int nVal(0); 
     double dVal(0.0); 

     if (ReadNums(sFileName, nVal, dVal)) 
     { 
      std::cout << "I read back " << nVal << " and " << dVal << "\n"; 
     } 
    } 
    return 0; 
} 
+0

outfile.open(「Robert_pay.out」);是我如何打開我的文件,我將嘗試infile >>數據。 – Robert 2011-04-13 17:08:19

+0

所以我應該像infile.get那樣獲得一個整數,還是另一種方法? – Robert 2011-04-13 17:16:40

+0

它不會讀取它始終保存在文件中間的所有數字 – Robert 2011-04-13 17:24:14

0

istream_iterator and ostream_iterator很有趣。

檢查出整齊的東西,你可以用它做。下面是一個華氏攝氏度轉換器的簡單例子,它讀取輸入並輸出:

#include <iostream> 
#include <iterator> 
#include <algorithm> 
#include <functional> 

using namespace std; 
typedef float input_type; 
static const input_type factor = 5.0f/9.0f; 

struct f_to_c : public unary_function<input_type, input_type> 
{ 
    input_type operator()(const input_type x) const 
    { return (x - 32) * factor; } 
}; 

int main(int argc, char* argv[]) 
{ 
// F to C 
    transform(
     istream_iterator<input_type>(cin), 
     istream_iterator<input_type>(), 
     ostream_iterator<input_type>(cout, "\n"), 
     f_to_c() 
    ); 

    return 0; 
} 
+0

這是一個非常酷的程序,但我不確定初學者(如Robert)會從中得到很多。 – 2011-04-13 17:50:11

+0

@Michael:好的,如果他理解了,那麼他會用C++編寫C程序,而不是用C編寫C程序。 – 2011-04-13 18:15:46