Как бы я вывел вывод из ВСЕГО кода выше? - PullRequest
0 голосов
/ 29 февраля 2012

По сути, я хочу, чтобы точная копия кода, который появляется в окне консоли, также выводилась в текстовый файл.

#include <conio.h>
#include <iostream>
#include <dos.h>
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <fstream>

using namespace std;

//Initialising gotoxy Comand
void gotoxy(int col, int row)
 {
  COORD coord;
  coord.X = col;
  coord.Y = row;
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
 }

int main()

 {

  char name1[20], name2[20], name3[30], name4[20];

  int funcNum = 0;
  int n1Nv, n1Mv, n1SEv, n1SWv;
  int n2Nv, n2Mv, n2SEv, n2SWv;
  int n3Nv, n3Mv, n3SEv, n3SWv;
  int n4Nv, n4Mv, n4SEv, n4SWv;
  int n1Total, n2Total, n3Total, n4Total, perTotal;

  double n1Per, n1PerTotal;
  double n2Per, n2PerTotal;
  double n3Per, n3PerTotal;
  double n4Per, n4PerTotal;
  double maxVote;

    //Introduction
    cout << "================================================================================";
    cout << "                              Ballot Results" << endl;
    cout << "                               Version 2.1" << endl;
    cout << "                          Created by Team b0nkaz" << endl;
    cout << "================================================================================" << endl;

    //Candidate Identification
    cout << "Enter the candidates running for president" << endl << endl;

    //cin.getline (workaround,30); //**

    cout << "Candidate One: ";
    cin.getline (name1,20);

    cout << "Candidate Two: ";
    cin.getline (name2,20);

    cout << "Candidate Three: ";
    cin.getline (name3,20);

    cout << "Candidate Four: ";
    cin.getline (name4,20);
    cout << " " << endl;

    //Separator
    cout << "--------------------------------------------------------------------------------" << endl;

    cout << "Input vote numbers from each region pressing enter after each input:" << endl << endl;

    //Separator
    cout << "--------------------------------------------------------------------------------" << endl;

    //Input Table
    //Regions
    gotoxy(22,19);
    cout << "North" << endl;
    gotoxy(31,19);
    cout << "Midlands" << endl;
    gotoxy(43,19);
    cout << "South East" << endl;
    gotoxy(57,19);
    cout << "South West" << endl;
    gotoxy(69,19);
    cout << "|  Total" << endl;
    cout << "_____________________________________________________________________|__________" << endl;
    gotoxy(69,21);
    cout << "|";
    gotoxy(69,22);
    cout << "|";
    gotoxy(69,23);
    cout << "|";
    gotoxy(69,24);
    cout << "|";
    gotoxy(69,25);
    cout << "|";
    gotoxy(69,25);
    cout << "|";
    gotoxy(69,26);
    cout << "|";
    gotoxy(69,27);
    cout << "|";
    gotoxy(69,28);
    cout << "|";
    gotoxy(69,29);
    cout << "|";

    //Candidates
    gotoxy(0,22);
    cout << name1;
    gotoxy(0,24);
    cout << name2;
    gotoxy(0,26);
    cout << name3;
    gotoxy(0,28);
    cout << name4;
    //Equals
    cout << endl;
    cout << "_____________________________________________________________________|__________" << endl;


    //Vote Input
    //North
    gotoxy(22,22);
    cin >> n1Nv;
    gotoxy(22,24);
    cin >> n2Nv;
    gotoxy(22,26);
    cin >> n3Nv;
    gotoxy(22,28);
    cin >> n4Nv;

    //Midlands
    gotoxy(31,22);
    cin >> n1Mv;
    gotoxy(31,24);
    cin >> n2Mv;
    gotoxy(31,26);
    cin >> n3Mv;
    gotoxy(31,28);
    cin >> n4Mv;

    //South East
    gotoxy(43,22);
    cin >> n1SEv;
    gotoxy(43,24);
    cin >> n2SEv;
    gotoxy(43,26);
    cin >> n3SEv;
    gotoxy(43,28);
    cin >> n4SEv;

    //South West
    gotoxy(57,22);
    cin >> n1SWv;
    gotoxy(57,24);
    cin >> n2SWv;
    gotoxy(57,26);
    cin >> n3SWv;
    gotoxy(57,28);
    cin >> n4SWv;

    //Total Votes
    //Name1
    gotoxy(72,22);
    n1Total = n1Nv + n1Mv + n1SEv + n1SWv;
    cout << n1Total;

    //Name2
    gotoxy(72,24);
    n2Total = n2Nv + n2Mv + n2SEv + n2SWv;
    cout << n2Total;

    //Name3
    gotoxy(72,26);
    n3Total = n3Nv + n3Mv + n3SEv + n3SWv;
    cout << n3Total;

    //Name4
    gotoxy(72,28);
    n4Total = n4Nv + n4Mv + n4SEv + n4SWv;
    cout << n4Total << endl << endl << endl;

    //Percentage Calculation
    perTotal = n1Total + n2Total + n3Total + n4Total;

    //Candidate One
    n1Per = n1Total*100;

    n1PerTotal = n1Per/perTotal;

    //Candidate Two
    n2Per = n2Total*100;

    n2PerTotal = n2Per/perTotal;

    //Candidate Three
    n3Per = n3Total*100;

    n3PerTotal = n3Per/perTotal;

    //Candidate Four
    n4Per = n4Total*100;

    n4PerTotal = n4Per/perTotal;

    cout << "Please wait for calculation..." << endl << endl;

    //Spinning Loading Line
    //std::cout << '-' << std::flush;
    //for(;;)

        //{
            //Sleep(100);
            //std::cout << "\b\\" << std::flush;
            //Sleep(100);
            //std::cout << "\b|" << std::flush;
            //Sleep(100);
            //std::cout << "\b/" << std::flush;
            //Sleep(100);
            //std::cout << "\b-" << std::flush;
        //}

    //Sleeping Program
    Sleep(1500); //1.5 secs

    //Total Output
    cout << "Candidate percentage:" << endl << endl;

    //Converting To One Decimal Place
    cout << fixed;
    std::cout.precision(1);

    //Vote Percentages
    cout << name1 << " = " << n1PerTotal << "%" << endl;
    cout << name2 << " = " << n2PerTotal << "%" << endl;
    cout << name3 << " = " << n3PerTotal << "%" << endl;
    cout << name4 << " = " << n4PerTotal << "%" << endl << endl;;

        //Calculating Winnner
        maxVote=n1PerTotal;
        if (n2PerTotal>maxVote)
        maxVote=n2PerTotal;
        if (n3PerTotal>maxVote)
        maxVote=n3PerTotal;
        if (n4PerTotal>maxVote)
        maxVote=n4PerTotal;

    //Separator
    cout << "--------------------------------------------------------------------------------" << endl;

    //Sleeping Program
    Sleep(1500); //1.5 secs

    if(maxVote==n1PerTotal)

      {
        cout << "     ***********************************************************************" << endl;
        cout << "        " << name1 << "                                                     " << endl;
        cout << "        is the new president of The British Society of IT Professionals     " << endl; 
        cout << "        with " << n1PerTotal << "% of the vote                              " << endl;
        cout << "     ***********************************************************************" << endl << endl;

    //Separator
    cout << "--------------------------------------------------------------------------------" << endl;
      }

    else if(maxVote==n2PerTotal)

      {
        cout << "     ***********************************************************************" << endl;
        cout << "        " << name2 << "                                                     " << endl;
        cout << "        is the new president of The British Society of IT Professionals     " << endl; 
        cout << "        with " << n2PerTotal << "% of the vote                              " << endl;
        cout << "     ***********************************************************************" << endl << endl;

    //Separator
    cout << "--------------------------------------------------------------------------------" << endl;
      }

    else if(maxVote==n3PerTotal)

      {
        cout << "     ***********************************************************************" << endl;
        cout << "        " << name3 << "                                                     " << endl;
        cout << "        is the new president of The British Society of IT Professionals     " << endl; 
        cout << "        with " << n3PerTotal << "% of the vote                              " << endl;
        cout << "     ***********************************************************************" << endl << endl;

    //Separator
    cout << "--------------------------------------------------------------------------------" << endl;
      }

    else if(maxVote==n4PerTotal)

      {
        cout << "     ***********************************************************************" << endl;
        cout << "        " << name4 << "                                                     " << endl;
        cout << "        is the new president of The British Society of IT Professionals     " << endl; 
        cout << "        with " << n4PerTotal << "% of the vote                              " << endl;
        cout << "     ***********************************************************************" << endl << endl;;

    //Separator
    cout << "--------------------------------------------------------------------------------" << endl;
      }

cout << "Press any key to exit..." << endl;

    getch();

//system("pause");
}

Я использую MS Visual Studio 2010, и любая помощь будет отличной! Обратите внимание, я все еще очень плохо знаком с C ++.

РЕДАКТИРОВАТЬ Я бы хотел видеть вывод в CMD, а также иметь отдельный текстовый файл с тем же кодом вывода. Все, что отображается в окне CMD, также копируется в текстовый файл.

Ответы [ 2 ]

1 голос
/ 29 февраля 2012

используйте оператор ofstream как таковой. По какой-то причине я не могу найти кнопку комментария, иначе я буду вовлечен в обсуждение выше ... но я отредактировал мой код ниже, чтобы отразить то, что, похоже, вызывает у вас беспокойство.

#include<fstream>

using namespace std;
int main()
{

ofstream fout;
fout.open("data.txt"); //Will create a new file if one is not already in existence
                       //You can put a static filename here or have them enter a string
                       //If you use a custom string your input will be "fout.open(STRING.c_str());
fout<<"Used exactly like cout from this point on";

fout.close(); //When you are done using it to close the file
}

Я решил назвать своего оператора ofout fout, потому что (хотя это не всегда хорошо), таким образом вы можете быстро изменить все свои cout на fout или скопировать их. Если пользователь вводит значение и вы хотите выплюнуть его обратно, вы можете использовать оператор ofstream после каждого cin.

Более подробную информацию о ofstream можно найти здесь ...

Надеюсь, это помогло!

0 голосов
/ 29 февраля 2012

Вы можете сделать это из-за пределов приложения, используя tee. tee принимает выходные данные программы и разделяет их на два потока (например, один в стандартный вывод и один в файл). К сожалению, Windows не поставляется с командой tee, но существует много реализаций .

Если вы хотите, чтобы это происходило из вашей программы, вы можете сделать эквивалент tee, используя пользовательский ofstream. Эта статья объясняет, как.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...