[英]C++: Simple fstream not writing to output file (not sure if it's taking the input file)
我有一個測試文件(“InputFile.txt”)保存了一些隨機信息以及一個空白輸出文件(“output.txt”)。 當我調試程序並檢查輸出文件時,它仍然是空白的。
“output.out”應該是“output.txt”(第25行)嗎? 我有問題,因為我在if語句的第22行有“InputFile.txt”作為cstring嗎? 這是正確的嗎? 到目前為止,我對fstream有點失落,請幫忙。
我的代碼:
#include<fstream>
#include<string>
#include<iomanip>
#include<iostream>
using namespace std;
int main()
{
ifstream InputFile;
ofstream OutputFile;
string lastName, firstName, fileName,
line;
int creditHours, state;
int tuition;
bool valid = false;
do{
cout << "Input file name (.txt): ";
cin >> fileName;
if(fileName == "InputFile.txt")
{
InputFile.open("InputFile.txt");
OutputFile.open("output.out");
valid = true;
}
else{
cout << "Invalid file name/type." << endl;
}
}while(valid == false);
OutputFile << "Last Name: " << ' ' << "First Name: " << ' '
<< "Credit Hours: " << ' ' << "Tuition Amount: " << endl;
while(!InputFile.eof()){
getline(cin, line);
InputFile >> firstName >> lastName >> creditHours >> state;
if(state == 1)
{
tuition = (creditHours * 350);
}
else
{
tuition = (creditHours * 570);
}
OutputFile << lastName << ' ' << firstName << ' '
<< creditHours << ' ' << tuition << endl;
}
InputFile.close();
OutputFile.close();
return 0;
}
嘗試這個
ifstream inFile;
ofstream outFile;
並打開你的文件進出模式
inFile.open("InputFile.txt", ios::in);
outFile.open("Output.txt",ios::out);
之后讀取Inputfile數據並將其寫入輸出文件
while (!inFile.eof()) {
inFile >> firstName >> lastName >> creditHours >> state;
outFile << firstName << " " << lastName<<" "<<creditHours<< " " <<state<<" "<< endl;
}
並以循環方式應用邏輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.