Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 06.12.2009, 22:56   #11
mihail0608
 
Регистрация: 04.12.2009
Сообщений: 7
По умолчанию

Вот попробовал совместить.. но выполняется только чересстрочное слияние, перестановки вообще не происходит..

Код:
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <iostream.h>
#include <conio.h>
#define LEN 1024

class myClass
{
public:
     void writeStr(char *str, FILE *in, FILE *out);
     void changeStr(char *str);
     void newFunc();
};
void myClass::changeStr(char *str)
{
   char st[300],*f,*l;
   char res[300];
   int lee;
   lee=strlen(str);
   int lf=0;
   f=strchr(str,' ');//naxogdenie dlinu
   lf=strlen(f);//    pervogo slova
   lf=lee-lf;//lenght of first word; (obwaj dlina-pos prevogo probela)
   cout<<"LF= "<<lf<<"\n";//out >> lenght of first word
//----------------------------------------------------------
   int ll=0;
   l=strrchr(str,' ');//naxogdenie dlinu
   ll=strlen(l)-1;//	poslednego slova
   cout<<"LL= "<<ll<<"\n";// out...
//-------------komponovka-----------------------
   int i=0;
   for (i=0;i<ll;i++)           //zapisuvaem v rezyltizyuwyu stroky
   res[i]=st[(lee-ll)+i];   //poslednee slovo (lee-ll) eto
   res[i]=0;                    //indeks na4ala poslednego slova
//-----------------------------------------------
   int j=0;// zdes zapisuvaem slova serediny stroki
   for(i=strlen(res),j=lf;j<lee-ll;i++,j++)
	res[i]=st[j];
	res[i]=0;
	//cout<<"\n\nOUT- "<<res;
//--------------------------
   for(i=strlen(res),j=0;j<lf;j++,i++)
	res[i]=st[j]; // eto zapis pervogo slova
	res[i]=0;         // v konec rezylt. stroki
	cout<<"\n\nOUT- "<<res;
getch();
}
void myClass::writeStr(char *str, FILE *in, FILE *out)
{
    if(fgets(str, LEN, in))
    {
      changeStr(str);
      fputs(str, out);
      if(str[strlen(str)-1]!='\n')
      fputc('\n', out);
    }
}

void myClass::newFunc()
{
  FILE *f1, *f2, *f3;
  char buf[LEN]="";
  char c1[20],c2[20],c3[20];
  clrscr();
  cout<<endl<<"Vvedite nazvanie file_1:"<<endl;
  cin>>c1;
  cout<<endl;
   if (!(f1=fopen (c1, "rt"))){
     cout<<"Error!!! File_1 ne otkrit!!!"<<endl;
     return;
   }
  clrscr();
  cout<<endl<<"Vvedite nazvanie file_2:"<<endl;
  cin>>c2;
  cout<<endl;
   if (!(f2=fopen (c2, "rt"))){
     cout<<"Error!! File_2 ne otkrit!!!"<<endl;
     return;
   }
  clrscr();
  cout<<endl<<"Vvedite nazvanie file_3:"<<endl;
  cin>>c3;
  cout<<endl;
   if (!(f3=fopen (c3, "wt"))) 	 {
     cout<<"Error!!! File_3 ne otkrit!!!"<<endl;
     return;
   }
  while(!feof(f1) || !feof(f2))
  {
    writeStr(buf, f1, f3);
    writeStr(buf, f2, f3);
  }
  cout<<endl<<"Gotovo!!! Rezul'tat v file "<<c3<<endl;
  fcloseall();
}

int main()
{
  myClass ob;
  ob.newFunc() ;
  return 0 ;
}
mihail0608 вне форума Ответить с цитированием
Старый 06.12.2009, 23:50   #12
forsaken66
Куды бечь?
Форумчанин
 
Аватар для forsaken66
 
Регистрация: 05.10.2009
Сообщений: 104
По умолчанию

Ну ясное дело, у тебя зачем в функции еще один char массив st[300]? Он же не нужен. Ты напрямую с *str которую передал оперируешь.
Вот вобщем, проверь это:

Код:
#include "string.h"
#include "stdio.h"
#include "ctype.h"
#include "iostream"
#include "conio.h"
#define LEN 1024

class myClass
{
public:
     void writeStr(char *str, FILE *in, FILE *out);
     void changeStr(char *str);
     void newFunc();
};
void myClass::changeStr(char *str)
{
   cout<<"Original string- "<<str;
   int zz;
   zz=strlen(str);
   str[zz]=0;
   char *f,*l;
   char res[50]="";
   int lee;
   lee=strlen(str);
   int lf=0;
   f=strchr(str,' ');//naxogdenie dlinu
   lf=strlen(f);//    pervogo slova
   lf=lee-lf;//lenght of first word; (obwaj dlina-pos prevogo probela)
//----------------------------------------------------------
   int ll=0;
   l=strrchr(str,' ');//naxogdenie dlinu
   ll=strlen(l)-1;//	poslednego slova
//-------------komponovka-----------------------
   int i=0;
   for (i=0;i<ll;i++)           //zapisuvaem v rezyltizyuwyu stroky
   res[i]=str[(lee-ll)+i];   //poslednee slovo (lee-ll) eto
   res[i]=0;                    //indeks na4ala poslednego slova
//-----------------------------------------------
   int j=0;// zdes zapisuvaem slova serediny stroki
   for(i=strlen(res),j=lf;j<lee-ll;i++,j++)
	res[i]=str[j];
	res[i]=0;
//--------------------------
   for(i=strlen(res),j=0;j<lf;j++,i++)
	res[i]=str[j]; // eto zapis pervogo slova
	res[i]=0;         // v konec rezylt. stroki
	cout<<"\n\nOUT- "<<res<<"\n\n";
}
void myClass::writeStr(char *str, FILE *in, FILE *out)
{
    if(fgets(str, LEN, in))
    {
      changeStr(str);
      fputs(str, out);
      if(str[strlen(str)-1]!='\n')
      fputc('\n', out);
    }
}

void myClass::newFunc()
{
  FILE *f1, *f2, *f3;
  char buf[LEN]="";
  char c1[20],c2[20],c3[20];
//------------------------------------------------------
  cout<<"\nVvedite nazvanie file_1: ";
  cin>>c1;
  cout<<endl;
   if (!(f1=fopen (c1, "rt")))
   {
     cout<<"Error!!! File_1 ne otkrit!!!"<<endl;
     return;
   }
  cout<<"\nVvedite nazvanie file_2: ";
  cin>>c2;
  cout<<endl;
   if (!(f2=fopen (c2, "rt")))
   {
     cout<<"Error!! File_2 ne otkrit!!!"<<endl;
     return;
   }
  cout<<"\nVvedite nazvanie file_3: ";
  cin>>c3;
  cout<<endl;
   if (!(f3=fopen (c3, "wt"))) 	 
   {
     cout<<"Error!!! File_3 ne otkrit!!!"<<endl;
     return;
   }
//--------------------------------------------------------
  while(!feof(f1) || !feof(f2))
  {
    writeStr(buf, f1, f3);
    writeStr(buf, f2, f3);
  }
  cout<<endl<<"Gotovo!!! Rezul'tat v file "<<c3<<endl;
  fcloseall();
}

int main()
{
  myClass ob;
  ob.newFunc() ;
  _getch();
  return 0 ;
}
Не хватало всего одного байта. Да-да, того самого, что из восьми бит состоит.

Последний раз редактировалось forsaken66; 06.12.2009 в 23:57. Причина: подправил малость =)
forsaken66 вне форума Ответить с цитированием
Старый 07.12.2009, 10:07   #13
mihail0608
 
Регистрация: 04.12.2009
Сообщений: 7
По умолчанию

forsaken66, в твоем виде компилиться.. но кроме слияния больше ничего не выполняется.. как думаешь может причина в массиве buf ??
Код:
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <iostream.h>
#include <conio.h>
#define LEN 1024

class myClass
{
public:
     void writeStr(char *str, FILE *in, FILE *out);
     void changeStr(char *str);
     void newFunc();
};
void myClass::changeStr(char *str)
{
   cout<<"Original string- "<<str;
   int zz;
   zz=strlen(str);
   str[zz]=0;
   char *f,*l;
   char res[50]="";
   int lee;
   lee=strlen(str);
   int lf=0;
   f=strchr(str,' ');//naxogdenie dlinu
   lf=strlen(f);//    pervogo slova
   lf=lee-lf;//lenght of first word; (obwaj dlina-pos prevogo probela)
//----------------------------------------------------------
   int ll=0;
   l=strrchr(str,' ');//naxogdenie dlinu
   ll=strlen(l)-1;//	poslednego slova
//-------------komponovka-----------------------
   int i=0;
   for (i=0;i<ll;i++)           //zapisuvaem v rezyltizyuwyu stroky
   res[i]=str[(lee-ll)+i];   //poslednee slovo (lee-ll) eto
   res[i]=0;                    //indeks na4ala poslednego slova
//-----------------------------------------------
   int j=0;// zdes zapisuvaem slova serediny stroki
   for(i=strlen(res),j=lf;j<lee-ll;i++,j++)
	res[i]=str[j];
	res[i]=0;
//--------------------------
   for(i=strlen(res),j=0;j<lf;j++,i++)
	res[i]=str[j]; // eto zapis pervogo slova
	res[i]=0;         // v konec rezylt. stroki
	cout<<"\n\nOUT- "<<res<<"\n\n";
}
void myClass::writeStr(char *str, FILE *in, FILE *out)
{
    if(fgets(str, LEN, in))
    {
      changeStr(str);
      fputs(str, out);
      if(str[strlen(str)-1]!='\n')
      fputc('\n', out);
    }
}

void myClass::newFunc()
{
  FILE *f1, *f2, *f3;
  char buf[LEN]="";
  char c1[20],c2[20],c3[20];
//------------------------------------------------------
  cout<<"\nVvedite nazvanie file_1: ";
  cin>>c1;
  cout<<endl;
   if (!(f1=fopen (c1, "rt")))
   {
     cout<<"Error!!! File_1 ne otkrit!!!"<<endl;
     return;
   }
  cout<<"\nVvedite nazvanie file_2: ";
  cin>>c2;
  cout<<endl;
   if (!(f2=fopen (c2, "rt")))
   {
     cout<<"Error!! File_2 ne otkrit!!!"<<endl;
     return;
   }
  cout<<"\nVvedite nazvanie file_3: ";
  cin>>c3;
  cout<<endl;
   if (!(f3=fopen (c3, "wt"))) 	 
   {
     cout<<"Error!!! File_3 ne otkrit!!!"<<endl;
     return;
   }
//--------------------------------------------------------
  while(!feof(f1) || !feof(f2))
  {
    writeStr(buf, f1, f3);
    writeStr(buf, f2, f3);
  }
  cout<<endl<<"Gotovo!!! Rezul'tat v file "<<c3<<endl;
  fcloseall();
}

int main()
{
  myClass ob;
  ob.newFunc() ;
   getch();
  return 0 ;
}

вот текстовые файлы после запуска данного кода
file_1.txt
Код:
In general, the population supported the military-political 
course of their public leadership. This It should be noted 
that one of the criteria for evaluation of their own 
governments residents United States and Europe consider the 
socio-economic achievements as well as security policies and 
relating to international crises.
Main trend, which has had an impact on the perception of U.S.
policy in Europe, has a certain improvement of Russo-American relations.
At the same time in the U.S. administration changed positions 
president is not always perceived positively.
Some political analysts agree that Obama went substantial concessions 
as a result of weakened Washington's position in relations with Russia.
file_2.txt
Код:
Socio-political activity of the population in the 
European region as a whole due to both inside 
and foreign policy of national leadership.
The most important factors which have influenced 
on the social situation in Europe, are the 
processes of European integration and the global 
financial crisis. So too tendency to revive the 
political participation of European countries which 
are most noticeable during election campaigns. So the 
result of parliamentary elections in Germany has 
been a transition of power from the coalition of CDU
mihail0608 вне форума Ответить с цитированием
Старый 07.12.2009, 10:08   #14
mihail0608
 
Регистрация: 04.12.2009
Сообщений: 7
По умолчанию

Выходной файл B.txt
Код:
In general, the population supported the military-political 
Socio-political activity of the population in the 
course of their public leadership. This It should be noted 
European region as a whole due to both inside 
that one of the criteria for evaluation of their own 
and foreign policy of national leadership.
governments residents United States and Europe consider the 
The most important factors which have influenced 
socio-economic achievements as well as security policies and 
on the social situation in Europe, are the 
relating to international crises.
processes of European integration and the global 
Main trend, which has had an impact on the perception of U.S.
financial crisis. So too tendency to revive the 
policy in Europe, has a certain improvement of Russo-American relations.
political participation of European countries which 
At the same time in the U.S. administration changed positions 
are most noticeable during election campaigns. So the 
president is not always perceived positively.
result of parliamentary elections in Germany has 
Some political analysts agree that Obama went substantial concessions 
been a transition of power from the coalition of CDU
as a result of weakened Washington's position in relations with Russia.
mihail0608 вне форума Ответить с цитированием
Старый 07.12.2009, 15:06   #15
forsaken66
Куды бечь?
Форумчанин
 
Аватар для forsaken66
 
Регистрация: 05.10.2009
Сообщений: 104
По умолчанию

Функция перестановки слов должна вернуть указатель на строку, с которой работала. Теперь вроде всё

Код:
#include "string.h"
#include "stdio.h"
#include "ctype.h"
#include "iostream"
#include "conio.h"
#define LEN 1024

class myClass
{
public:
     void writeStr(char *str, FILE *in, FILE *out);
     char* changeStr(char *str);
     void newFunc();
};
char* myClass::changeStr(char *str)
{
   cout<<"Original string- "<<str;
   int zz;
   zz=strlen(str);
   str[zz]=0;
   char *f,*l;
   char *res="";
   int lee;
   res=new char[50];
   lee=strlen(str);
   int lf=0;
   f=strchr(str,' ');//naxogdenie dlinu
   lf=strlen(f);//    pervogo slova
   lf=lee-lf;//lenght of first word; (obwaj dlina-pos prevogo probela)
//----------------------------------------------------------
   int ll=0;
   l=strrchr(str,' ');//naxogdenie dlinu
   ll=strlen(l)-1;//	poslednego slova
//-------------komponovka-----------------------
   int i=0;
   for (i=0;i<ll-1;i++)           //zapisuvaem v rezyltizyuwyu stroky
   res[i]=str[(lee-ll)+i];   //poslednee slovo (lee-ll) eto
   res[i]=0;                    //indeks na4ala poslednego slova
//-----------------------------------------------
   int j=0;// zdes zapisuvaem slova serediny stroki
   for(i=strlen(res),j=lf;j<lee-ll;i++,j++)
	res[i]=str[j];
	res[i]=0;
//--------------------------
   for(i=strlen(res),j=0;j<lf;j++,i++)
	res[i]=str[j]; // eto zapis pervogo slova
	res[i]=0;         // v konec rezylt. stroki
	str=(char*)res;
	//cout<<"OUT- "<<str<<"\n";
return str;
}
void myClass::writeStr(char *str, FILE *in, FILE *out)
{
    if(fgets(str, LEN, in))
    {
      str=changeStr(str);
	  fputs(str, out);
	  cout<<"Outstring- "<<str<<" \n\n\n\n";
      if(str[strlen(str)-1]!='\n')
      fputc('\n', out);
    }
}

void myClass::newFunc()
{
  FILE *f1, *f2, *f3;
  char buf[LEN]="";
  char c1[20],c2[20],c3[20];
//------------------------------------------------------
  cout<<"\nVvedite nazvanie file_1: ";
  cin>>c1;
  cout<<endl;
   if (!(f1=fopen (c1, "rt")))
   {
     cout<<"Error!!! File_1 ne otkrit!!!"<<endl;
     return;
   }
  cout<<"\nVvedite nazvanie file_2: ";
  cin>>c2;
  cout<<endl;
   if (!(f2=fopen (c2, "rt")))
   {
     cout<<"Error!! File_2 ne otkrit!!!"<<endl;
     return;
   }
  cout<<"\nVvedite nazvanie file_3: ";
  cin>>c3;
  cout<<endl;
   if (!(f3=fopen (c3, "wt"))) 	 
   {
     cout<<"Error!!! File_3 ne otkrit!!!"<<endl;
     return;
   }
//--------------------------------------------------------
  while(!feof(f1) || !feof(f2))
  {
    writeStr(buf, f1, f3);
    writeStr(buf, f2, f3);
  }
  cout<<endl<<"Gotovo!!! Rezul'tat v file "<<c3<<endl;
  fcloseall();
}

int main()
{
  myClass ob;
  ob.newFunc() ;
  getch();
  return 0 ;
}
И еще, когда находим длину последнего слова, затем в цикле
Код:
for (i=0;i<ll-1;i++)
пишем ll-1, если просто ll то захватывается символ конца строки. И еще вопрос к старшим товарищам - почему такая конструкция не дает нужного результата.
Код:
void az(char* z)
{
//как нибудь изменяем z
}
main ()
{
  // z="Hell O!"
 az(z);
cout<<z; // а z - то все равно "Hell O!"
}
Сделать то я сделал но не до конца понял
Не хватало всего одного байта. Да-да, того самого, что из восьми бит состоит.
forsaken66 вне форума Ответить с цитированием
Старый 08.12.2009, 15:50   #16
mihail0608
 
Регистрация: 04.12.2009
Сообщений: 7
По умолчанию

forsaken66, спасибо огромное!!!
Объясни пожалуйста некоторые места в программе
Код:
     char* changeStr(char *str); \\ почему перед char тоже указатель стоит
     void newFunc();
};
char* myClass::changeStr(char *str) \\\\ почему перед char тоже указатель стоит
{
   cout<<"Original string- "<<str;
   int zz;
   zz=strlen(str);
   str[zz]=0;
   char *f,*l;
   char *res="";
   int lee;
   res=new char[50]; \\вот new char как понять?? new это к ооп или к шаблонам отнсится??
   lee=strlen(str);
   int lf=0;
   f=strchr(str,' ');//naxogdenie dlinu
   lf=strlen(f);//    pervogo slova
   lf=lee-lf;//lenght of first word; (obwaj dlina-pos prevogo probela)
//----------------------------------------------------------
   int ll=0;
   l=strrchr(str,' ');//naxogdenie dlinu
   ll=strlen(l)-1;//	poslednego slova
//-------------komponovka-----------------------
   int i=0;
   for (i=0;i<ll-1;i++)           //zapisuvaem v rezyltizyuwyu stroky
   res[i]=str[(lee-ll)+i];   //poslednee slovo (lee-ll) eto
   res[i]=0;                    //indeks na4ala poslednego slova
//-----------------------------------------------
   int j=0;// zdes zapisuvaem slova serediny stroki
   for(i=strlen(res),j=lf;j<lee-ll;i++,j++)
	res[i]=str[j];
	res[i]=0;
//--------------------------
   for(i=strlen(res),j=0;j<lf;j++,i++)
	res[i]=str[j]; // eto zapis pervogo slova
	res[i]=0;         // v konec rezylt. stroki
	str=(char*)res;
	//cout<<"OUT- "<<str<<"\n";
return str;
}
mihail0608 вне форума Ответить с цитированием
Старый 08.12.2009, 16:25   #17
forsaken66
Куды бечь?
Форумчанин
 
Аватар для forsaken66
 
Регистрация: 05.10.2009
Сообщений: 104
По умолчанию

Код:
char* myClass::changeStr(char *str)
Здесь первое char* myClass:: - это тип, который возвращает функция (в нашем случае это указатель на строку, char*).
changeStr(char *str) - здесь в скобках мы указываем какой тип будет принимать функция (тоже указатель на строку, char*).
т. е. мы "скармливаем" функции указатель на строку(прочитанную из файла в данном случае), в самой функции обрабатываем строку, и по итогу мы должны возвратить результат работы(измененную строку). поэтому ставим в конце функции return str;
Не хватало всего одного байта. Да-да, того самого, что из восьми бит состоит.
forsaken66 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
СИ. Удалить слова, которые содержат все повторяющиеся буквы первого слова nick23 Помощь студентам 7 01.11.2009 14:47
Минимальная длинна слова в строке Anarki Общие вопросы C/C++ 7 24.09.2009 20:39
Замена одного слова в string строке. Samopal Паскаль, Turbo Pascal, PascalABC.NET 8 19.04.2009 08:03
Указание последнего в строке значения прерывистого ряда значений. Baloo007 Microsoft Office Excel 10 06.08.2008 15:20
написать с помощью рекурсии функцию поиска последнего слова в строке? - Си Cvetok Помощь студентам 1 13.05.2008 15:43