Как сделать функцию вывода для записи форматированного вывода как на экран, так и в файл вывода
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
void getInformationKeyBoard(int, string[], int[]);
bool openFile(ifstream &infile, string fileName);
void display(int size, string array[]);
void read2Array(ifstream &infile, int size, string array[]);
void printReport(string name[], int score[], int NumberOfStudent);
int main()
{
const int size = 1024;
string Name[size], scoreFile[size];
int score[size];
int NumberOfStudent;
const int SIZE = 7;
ifstream inFile;
char choice;
cout << "You want to enter your scores by your keyboard (A) or from your input (B): ";
cin >> choice;
if (choice == 'a' || choice == 'A') // It will take information from keyboard
{
cout << "How many students do you want to enter: ";
cin >> NumberOfStudent;
getInformationKeyBoard(NumberOfStudent, Name, score);
printReport(Name, score, NumberOfStudent);
}
else if (choice == 'b' || choice == 'B') // It will take information from file
{
string name;
char again = 'Y';
bool close = false;
cout << "Enter name of file: ";
cin >> name;
openFile(inFile, name);
read2Array(inFile, SIZE, scoreFile);
display(SIZE, scoreFile);
}
else // If you choice is not A,a or B,b
cout << "Your did not follow the right instruction.";
cout << endl << endl;
system("pause");
return 0;
}
// Open file
bool openFile(ifstream &infile, string fileName){
infile.open(fileName);
if (infile)
return true;
return false;
}
void getInformationKeyBoard(int size, string Names[], int scores[]) // Information from keyboard
{
for (int i = 0; i < size; i++)
{
cout << i + 1 << ". Student First Name and Last Name: ";
cin.ignore();
getline(cin, Names[i]);
do
{
cout << i + 1 << ". Enter the score between 1 and 100: ";
cin >> scores[i];
} while (scores[i] > 100 || scores[i] < 0);
}
}
void read2Array(ifstream &infile, int size, string array[]){
int index = 0;
string line;
while (getline(infile, line)){
array[index] = line;
++index;
}
}
// Display array
void display(int size, string array[]){
for (int index = 0; index < size; ++index){
cout << array[index] << endl;
}
}
void printReport(string name[], int score[], int NumberOfStudent)
{
int lowest, highest, mean;
cout << "Enter lowest score: ";
cin >> lowest;
cout << "Enter highest score: ";
cin >> highest;
cout << "Enter mean score: ";
cin >> mean;
cout << "================================================================================";
cout << setw(10) << "Number of scores = " << NumberOfStudent << endl;
cout << setw(10) << "Lowest Score = " << lowest << endl;
cout << setw(10) << "Highest Score = " << highest << endl;
cout << setw(10) << "Mean Score = " << mean << endl;
cout << "Name" << setw(15) << "Score" << setw(15) << "IsLowest" << setw(15) << "IsHighest" << setw(15) << "Mean" << endl;
cout << "-----------------------------------------------------------------" << endl;
cout << name[NumberOfStudent] << endl;
cout << endl;
}
Раздел статистики заголовка с количеством баллов, наименьшим, наивысшим и средним баллами, за которым следуют подробности для каждого учащегося - по одному на строку.
Я застрял при выводе на экран. Я хочу, чтобы мой вывод выглядел так
Number of scores = 3 Lowest Score = 82 Highest Score = 92 Mean Score = 87 Name Score IsLowest IsHighest >=Mean F1 L1 82 Y N N F2 L2 87 N N Y F3 L3 92 N Y Y
2 ответа
Возможно, вы могли бы передать объект ostream в качестве параметра, а затем заменить все вхождения cout в вашей функции именем этого аргумента. Тогда вы можете запустить функцию дважды
printReport(cout, other args);
printReport(outFile, other args);
(Или настройте функцию на вызов самой себя, чтобы вам не приходилось каждый раз вводить cout). Единственная проблема с этим методом в том, что я вижу, что вы получаете ввод, находясь внутри функции. Если вы хотите использовать описанный выше метод, вам придется передвинуть некоторые вещи. Вместо этого я бы настроил другую функцию, которая принимает строку в качестве входных данных и вставляет указанную строку как в cout, так и в ваш файл. Так что вместо того, чтобы писать
cout<<"hi";
file<<"hi";
Вы могли бы сделать
...
functionName("hi", outfile);
...
void functionName(string str, ostream outfile)
{
cout<<str;
outfile<<str;
}
Надеюсь это поможет
Как правило, следующая функция будет работать для репликации вывода консоли в файл.
#include <stdarg.h> /* va_list, va_start, va_arg, va_end */
void print(FILE *f, char const *fmt, ...) {
va_list ap;
//Normal console print
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
//Printing to file
if (f != NULL) {
va_start(ap, fmt);
vfprintf(f, fmt, ap);
va_end(ap);
}
}
Если вы хотите только консольный вывод, просто
print(NULL, "%d\t%d\n", 1, 100);//include any needed C style formatting here
Если вы хотите, чтобы вывод консоли был сохранен в файл, просто передайте соответствующий указатель файла в качестве первого аргумента.
FILE *fp = fopen("logfile.txt","a");
print(fp, "%d\t%d\n, 1, 100);//logs the console output to logfile.txt
Форматирование окна консоли также будет сохранено в текстовом файле.