2015-04-22 74 views
0

我有以下代碼寫入空白與C++文件

void print(int & a, double & b, string & c) 
{ 
    cout << setprecision(2) << fixed; 
    const double GPA = a/b; 
    if(c == "Y") 
    { 
     cout << "\n\nTotal number of credit hours: " << a << endl; 
    } 
    else 
    { 
     cout << "\n*** Grades are being held for not paying the tuition. ***" 
    } 
} 

我怎麼能寫在print(int, double, string)cout到一個文本文件,而無需與print(int, double, string);篡改?我試過這樣的東西

ofstream file; 
file.open("file.txt"); 
file << print(a,b,c); 
file.close(); 
cout << "file created" << endl; 

但這不能編譯。爲什麼不,我如何解決它?

+0

(OT)函數應該通過值或const引用傳遞a,b,c,因爲它不會修改它們 –

+0

@Christian您提出的編輯是不恰當的。不要將代碼添加到問題中。 –

回答

7

您編寫它的方式,您的print()函數不能輸出到任何給定的流。這是因爲它將寫入的流硬編碼爲cout

如果您希望它能夠寫入任何給定的流,則必須將流參數化爲另一個函數參數。對於(1)方便和(2)與現有的,它假定print()只需要三個參數並寫入cout代碼的兼容性,可以使可選的新參數的默認它cout

void print(int& a, double& b, string& c, ofstream& os=cout) { 
    os << setprecision(2) << fixed; 
    const double GPA = a/b; 
    if (c == "Y") { 
     os << "\n\nTotal number of credit hours: " << a << endl; 
    } else { 
     os << "\n*** Grades are being held for not paying the tuition. ***"; 
    } 
} 

然後你可以叫它如下所示:

print(a,b,c,file); 

您的代碼無法編譯的原因是您無法將void作爲函數參數或運算符操作數傳遞。當一個函數被聲明爲返回void時,表示它根本不返回任何東西。沒有數據返回print()流到流中。流發生在函數內部,所以只能在那裏選擇輸出將被寫入的流。

+0

是否有我必須包含的標題?該cout得到了強調。 –

+1

你必須'#include ',並且如果你想使用'std'命名空間下定義的名字(比如'cout')而沒有限制,那麼你必須指定'using namespace std;'。或者,您可以限定它們,例如'std :: cout'。 – bgoldst

2

bgoldst的答案解決了問題,但我建議一個完全不同的解決方案。把你的數據放在一個operator<<超載的類中。

struct class_results { 
    int credits; 
    double GP_total; 
    bool tuition_paid; 
}; 
std::ostream& operator<<(std::ostream& out, const class_results& c) { 
    if (c.tuition_paid) { 
     const double GPA = c.credits/c.GP_total; 
     out << "Total number of credit hours: "; 
     out << setprecision(2) << fixed << c.credits<< '\n'; 
    } else 
     out << "\n*** Grades are being held for not paying the tuition. ***" 
    return out; 
} 

然後使用稍微正常:

class_results results = {num_credits,GPTottal,tuition}; 
ofstream file; 
file.open("file.txt"); 
file << results; 
file.close(); 
cout << "file created" << endl; 
1

我怎麼能寫在print(int, double, string)cout到一個文本文件,而無需與print(int, double, string);篡改?

你不能。

函數print已損壞,如果不修復它,你就無法做你想做的事。