Модераторы: bsa
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> передача параметров при работе с файлами 
:(
    Опции темы
mary1010
  Дата 23.12.2012, 16:05 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 17
Регистрация: 20.12.2012

Репутация: нет
Всего: нет



есть программка, которая первое и среднее слово в каждой строке файла меняет местами
Код

#include <fstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <sstream>
#include <vcl.h>
#include <iostream>
#include <conio.h>
 
#pragma hdrstop
using namespace std;
 
int main()
{
//entering a file name using keyboard
 cout << "Enter a processed file name:"  ;
std::string name;
std::cin >> name;
std::ifstream ifs(name.c_str());
 
cout << "Enter a final file name:"  ;
std::string name1;
std::cin >> name1;
std::ofstream o(name1.c_str());
 
 
if (! ifs && ! o)
 
        {  cout<<"wrong file name!";
           exit (1);    }
 
  else{
   
    if (!ifs) return 1;
    std::string str;
    while (!ifs.eof() && std::getline(ifs, str))
    {
        std::istringstream ist(str);
        std::vector<std::string> v;
        std::copy(std::istream_iterator<std::string>(ist),
                  std::istream_iterator<std::string>(), std::back_inserter(v));
        std::swap(*v.begin(), *(v.begin() + v.size() / 2));
        std::copy(v.begin(), v.end(), std::ostream_iterator<std::string> (o, " "));
        o << std::endl;
    } }
    system("pause");
    return 0;
 
    }


мне необходимо доработать ее, чтобы программа состояла из подпрограмм и имела текстовое меню:
Код

int showMenu()
   {
 
int command = 0;
while(true)
       
       {
 
cout << "1. changing of the first and average word in a line of the file " << endl;
cout << "2. see result" << endl;
cout << "3. Exit" << endl;
 
cin >> command;
if (command >=1 && command <=3) return command;
cout << "You have entered a wrong command. Please repeat your choice:" << endl;
 
     if (cin.fail())
  {
     cin.clear();
     cin.sync();
                     }
                              }
         }


помогите, пожалуйста описать сase(ы) и подскажите как передать параметры в void()??
PM MAIL   Вверх
Snake174
Дата 24.12.2012, 10:31 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 36
Регистрация: 5.10.2011
Где: Miass

Репутация: нет
Всего: нет



Код

int showMenu()
{
  int command = 0;
  
  while(true)     
  { 
    cout << "1. changing of the first and average word in a line of the file " << endl;
    cout << "2. see result" << endl;
    cout << "3. Exit" << endl;
 
    cin >> command;
    
    if (command >=1 && command <=3)
    { 
      cout << "You have entered a wrong command. Please repeat your choice:" << endl;
      return command;
    }
 
    if (cin.fail())
    {
      cin.clear();
      cin.sync();
    }

    switch (command)
    {
      case 1:
      {
        //entering a file name using keyboard
        cout << "Enter a processed file name:"  ;
        std::string name;
        std::cin >> name;
        std::ifstream ifs(name.c_str());
 
        cout << "Enter a final file name:"  ;
        std::string name1;
        std::cin >> name1;
        std::ofstream o(name1.c_str());
 
        if (!ifs && !o)
        {  
          cout<<"wrong file name!";
          exit (1);    
        }
        else
        {  
          if (!ifs) 
            return 1;
    
         std::string str;
     
         while (!ifs.eof() && std::getline(ifs, str))
         {
           std::istringstream ist(str);
           std::vector<std::string> v;
           std::copy(std::istream_iterator<std::string>(ist),
                          std::istream_iterator<std::string>(), std::back_inserter(v));
           std::swap(*v.begin(), *(v.begin() + v.size() / 2));
           std::copy(v.begin(), v.end(), std::ostream_iterator<std::string> (o, " "));
           o << std::endl;
         } 
       }

       break;
     }

     case 2:
       open file for read
       read file
       display data
       close file
       break;

     case 3:
       exit(0);
    }
  }
}


Цитата

как передать параметры в void()??

Какие параметры? Какой void() ?????????


Это сообщение отредактировал(а) Snake174 - 24.12.2012, 10:33
PM MAIL   Вверх
mary1010
Дата 24.12.2012, 19:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 17
Регистрация: 20.12.2012

Репутация: нет
Всего: нет



Snake174, ну void для подпрограмм или функциями их еще называют
Код

void EnterFileName1(const char*);
......
 void EnterFileName1(const char*std)
       {
        std::string name;
        std::cin >> name;
        std::ifstream ifs(name.c_str());
                                                }


как-то так....но это не правильно

а вот весь код, но в нем куча ошибок....
Код

#include <fstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <sstream>
#include <vcl.h>
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <ctime>


#pragma hdrstop
using namespace std;
#pragma argsused

void EnterFileName1(const char*);
void EnterFileName2(const char*);
void ProcessingFile();
void result(char*, char*);
void ShowMenu();

        void EnterFileName1(const char*std)
       {
        std::string name;
        std::cin >> name;
        std::ifstream ifs(name.c_str());
                                                }

        void EnterFileName2(const char*std)
       {
        std::string name1;
        std::cin >> name1;
        std::ofstream o(name1.c_str());
                                                }

             void ProcessingFile(char*std, char*o)
       {
       if (!ifs) return 1;
         std::string str;
         while (!ifs.eof() && std::getline(ifs, str))
    {
        std::istringstream ist(str);
        std::vector<std::string> v;
        std::copy(std::istream_iterator<std::string>(ist),
                  std::istream_iterator<std::string>(), std::back_inserter(v));
        std::swap(*v.begin(), *(v.begin() + v.size() / 2));
        std::copy(v.begin(), v.end(), std::ostream_iterator<std::string> (o, " "));
        o << std::endl;
    }
        }


        void result(char*text, char*buf)
    {
    char text[500], buf[500];
    cout << "Enter the final name  file: ";
    cin >> text;
    ifstream f(text, ios::in);
    if (!f)  {
                cout << "Error of opening of a file.";
        }
        while (!f.eof())  {
              f.getline(buf, 500);
              cout << buf  << endl;
                   }

       int main()

 cout << "Welcome! Enter a command:"<< endl;
 int command = showMenu();
 switch (command)

             {
                case 1:
                cout << "Enter a processed file name:"<<endl  ;
                EnterFileName1(const char*str);
                cout << "Enter a final file name:"<<endl   ;
                EnterFileName2(const char*str);
                 std::ofstream o(name1.c_str());
                  if (! ifs && ! o)

        {  cout<<"wrong file name!";
           exit (1);    }

  else { ProcessingFile(char*str)
        cout << "change of the file is successfully complete!"<<endl  ;  }
           break;

                case 2:
                void result(char*text, char*buf)
                break;

                case 3:
                return;
                break;

                          }
      void ShowMenu();
    {
        int command = 0;
        while(true){

                cout << "1. changing of the first and average word in a line of the file " << endl;
                cout << "2. see result" << endl;
                cout << "3. Exit" << endl;

        cin >> command;
        if (command >=1 && command <=3) return command;
        cout << "You have entered a wrong command. Please repeat your choice:" << endl;

                if (cin.fail()){
                  cin.clear();
                  cin.sync();
                }
        }
    }



Это сообщение отредактировал(а) mary1010 - 24.12.2012, 19:21
PM MAIL   Вверх
Snake174
Дата 25.12.2012, 05:44 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 36
Регистрация: 5.10.2011
Где: Miass

Репутация: нет
Всего: нет



Код

#include <fstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <ctime>

//=============================================================================
const char *EnterFileName1();
const char *EnterFileName2();
void ProcessingFile( std::ifstream &ifs, const char *outName );
void result();
int ShowMenu();
//=============================================================================
const char *EnterFileName1()
{
  std::string name;
  std::cin >> name;

  return name.c_str();
}
//=============================================================================
const char *EnterFileName2()
{
  std::string name;
  std::cin >> name;

  return name.c_str();
}
//=============================================================================
void ProcessingFile( std::ifstream &ifs, const char *outName )
{
  std::ofstream o( outName );

  if (o.bad())
  {
    std::cout << "Wrong output file name." << std::endl;
    return;
  }

  std::string str;

  while (!ifs.eof() && std::getline( ifs, str ))
  {
    std::istringstream ist( str );
    std::vector<std::string> v;
    std::copy( std::istream_iterator<std::string>( ist ),
               std::istream_iterator<std::string>(), std::back_inserter(v) );
    std::swap( *v.begin(), *(v.begin() + v.size() / 2) );
    std::copy( v.begin(), v.end(), std::ostream_iterator<std::string> (o, " ") );
    o << std::endl;
  }

  o.close();

  std::cout << "Change of the file is successfully complete!" << std::endl;
}
//=============================================================================
void result()
{
  char text[500], buf[500];
  std::cout << "Enter the final name  file: ";
  std::cin >> text;
  std::ifstream f( text, std::ios::in );

  if (f.bad())
  {
    std::cout << "Error of opening of a file." << std::endl;
  }

  while (!f.eof())
  {
    f.getline( buf, 500 );
    std::cout << buf  << std::endl;
  }

  f.close();
}
//=============================================================================
int ShowMenu()
{
  int command = 0;

  while (true)
  {
    std::cout << "1. Changing of the first and average word in a line of the file" << std::endl;
    std::cout << "2. See result" << std::endl;
    std::cout << "3. Exit" << std::endl;
    std::cin >> command;

    if (command >=1 && command <=3)
      return command;

    std::cout << "You have entered a wrong command. Please repeat your choice: " << std::endl;

    if (std::cin.fail())
    {
      std::cin.clear();
      std::cin.sync();
    }
  }

  return -1;
}
//=============================================================================
int main()
{
  std::cout << "Welcome! Enter a command: "<< std::endl;

  int command = ShowMenu();

  switch (command)
  {
    case 1:
    {
      std::cout << "Enter a processed file name: " << std::endl;
      std::ifstream ifs( EnterFileName1() );
      std::cout << "Enter a final file name: " << std::endl;
      const char *outName = EnterFileName2();

      if (ifs.bad())
      {
        std::cout << "Wrong input file name!";
        exit(1);
      }
      else
      {
        ProcessingFile( ifs, outName );
        ifs.close();
      }

      break;
    }

    case 2:
      result();
      break;

    case 3:
      exit(0);
  }

  return 0;
}
//=============================================================================


Цитата

Snake174, ну void для подпрограмм или функциями их еще называют

Код

void PrintFileName( const char *name )
{
  std::cout << name << std::endl;
}

int main()
{
  const char *fileName = "zzz.txt";
  PrintFileName( fileName );

  return 0;
}

PM MAIL   Вверх
mary1010
Дата 25.12.2012, 23:40 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 17
Регистрация: 20.12.2012

Репутация: нет
Всего: нет



Snake174, спасибо Вам!)
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "C/C++: Для новичков"
JackYF
bsa

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Для новичков | Следующая тема »


 




[ Время генерации скрипта: 0.0927 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.