Thread: Another homework assiment..

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    57

    Another homework assiment..

    Hi.. I have been given an filestreaming assiment. We sopostu make a program that open a .txt file with something in it, then we have to randomly regenerate exactly same content. The file is over 8000 characters and it has to pass a test off even higher number. So far i have been working on this for a long time and i got to thsi and i am stuck plz help Thanks.

    Code:
    void Survival_of_the_Fittest ()
    {
         int exit=0;//the abort variable
         int flag=0;//the flag for the count of characters right
         int lem_length=1;//the lengh of the file needs to be reproduced
         char ch_lem;//buffer char
         char ch_copy;//buffer char
         char random;//the randomly generated char 
         int location;//the location to write to
         
         time_t seconds;//seeding the time for randomly generating
         time(&seconds);
         srand(seconds); 
         
         
         while (flag!=lem_length)//while count is not lengh
         {
               ifstream icopy;//creat the read file
               ofstream outfile;//creat the out file
               icopy.open("tempsecond.txt");//open read
               outfile.open("temp.txt");//open write
               
               ifstream ilemony;//the file that needs to be reproduced
               ilemony.open("lemony.txt");//open it
         
               ilemony.seekg(0,ios::end);//put the pointor to the end
               lem_length=ilemony.tellg();//assign the number of chars to length
               
               ilemony.seekg(0);//put to begining
               icopy.seekg(0);
               //flag=0;
               
               while (!ilemony.eof())//while the original file not end of file
               {
                     ilemony.get(ch_lem);//get ch from original
                     icopy.get(ch_copy);//get ch from read
                     
                     if (ch_lem==ch_copy)//if ch read same as ch original
                     {
                          flag++;//add one to count
                     }
                     else 
                     {  
                          random=rand()% 96 + 32;//generate all the characters
                          if (random==127)//if 127 which is useless
                             random=10;   //then change to end line
                          location=ilemony.tellg();//get the location we are at
                          outfile.seekp(location);//put the write file pointer to location  
                          outfile<<random;//print into the file
                     }
               }
               cout<<"The number correct is: "<<flag<<endl;//output the correct number
               ilemony.close();//close original
               outfile.close();//close out
               icopy.close();//close read
               Copyfrom("temp.txt","tempsecond.txt");//make them exactly same
         }
    }
    
    void Copyfrom(string from_name, string to_name)
    {
          char ch;//buffer
          int from_length;//length
          
          ofstream to;//creates file
          to.open(to_name.c_str());
          
          ifstream from;//creats another one
          from.open(from_name.c_str());
          
          assert (!from.fail());//check that not fail to open
          assert (!to.fail());
             
          from.seekg(0);
          
          while(! from.eof()) //till not end of file
          {
                  from.get(ch);//print that
                  to<<ch;
          }
          to.close();//close them both
          from.close();
    }
    k after i ran this here the beggining of the files

    Original
    Code:
    If you are interested in stories with happy endings, you would be better off reading some other book.
    Final one is
    Code:
    O  &  P  U  j  o  `  
     \  '  R  }  )  ,  8  g  V  $  u  f  9  \  o  V  N  .  E  J  k  (  c  1  6  j  t  8  6  o  w  p  g  Q  5  q  r  '  R  _  [  p  b  ,  ]  T  >  ^  S  h  7  R  y
    So for some reason it puts spaces everywhere and it also does not match in now way. Plz help lol all i can say Hope my commenting is good and format is ok. Thanks let me know if some type of method is bad and if i can be improved anywhere. Thanks again.

  2. #2
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    well, seeing as you didn't give enough code to even give us the errors you're getting or the files you're using, I used this code:
    Code:
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <cstdlib>
    #include <cassert>
    
    using namespace std;
    
    void Survival_of_the_Fittest();
    void Copyfrom(string from_name, string to_name);
    
    int main()
    {
    	Survival_of_the_Fittest();
    	return 0;
    }
    
    void Survival_of_the_Fittest ()
    {
         int exit=0;//the abort variable
         int flag=0;//the flag for the count of characters right
         int lem_length=1;//the lengh of the file needs to be reproduced
         char ch_lem;//buffer char
         char ch_copy;//buffer char
         char random;//the randomly generated char 
         int location;//the location to write to
         
         time_t seconds;//seeding the time for randomly generating
         time(&seconds);
         srand(seconds); 
         
         
         while (flag!=lem_length)//while count is not lengh
         {
               ifstream icopy;//creat the read file
               ofstream outfile;//creat the out file
               icopy.open("tempsecond.txt");//open read
               outfile.open("temp.txt");//open write
               
               ifstream ilemony;//the file that needs to be reproduced
               ilemony.open("lemony.txt");//open it
         
               ilemony.seekg(0,ios::end);//put the pointor to the end
               lem_length=ilemony.tellg();//assign the number of chars to length
               
               ilemony.seekg(0);//put to begining
               icopy.seekg(0);
               //flag=0;
               
               while (!ilemony.eof())//while the original file not end of file
               {
                     ilemony.get(ch_lem);//get ch from original
                     icopy.get(ch_copy);//get ch from read
                     
                     if (ch_lem==ch_copy)//if ch read same as ch original
                     {
                          flag++;//add one to count
                     }
                     else 
                     {  
                          random=rand()% 96 + 32;//generate all the characters
                          if (random==127)//if 127 which is useless
                             random=10;   //then change to end line
                          location=ilemony.tellg();//get the location we are at
                          outfile.seekp(location);//put the write file pointer to location  
                          outfile<<random;//print into the file
                     }
               }
               cout<<"The number correct is: "<<flag<<endl;//output the correct number
               ilemony.close();//close original
               outfile.close();//close out
               icopy.close();//close read
               Copyfrom("temp.txt","tempsecond.txt");//make them exactly same
         }
    }
    
    void Copyfrom(string from_name, string to_name)
    {
          char ch;//buffer
          int from_length;//length
          
          ofstream to;//creates file
          to.open(to_name.c_str());
          
          ifstream from;//creats another one
          from.open(from_name.c_str());
          
          assert (!from.fail());//check that not fail to open
          assert (!to.fail());
             
          from.seekg(0);
          
          while(! from.eof()) //till not end of file
          {
                  from.get(ch);//print that
                  to<<ch;
          }
          to.close();//close them both
          from.close();
    }
    with this file:
    Code:
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sollicitudin ante et nisi. Suspendisse potenti. Donec viverra neque sed orci. Nullam suscipit dolor vitae turpis. Aenean nisi. Phasellus feugiat, ante nec semper aliquet, augue dolor cursus purus, sit amet vestibulum magna purus et est. In laoreet, est nec vestibulum lobortis, ligula augue gravida neque, et malesuada risus ipsum sit amet est. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In semper. Praesent sed eros eget tellus venenatis euismod. Donec posuere metus eu dui. Vivamus nec tortor.
    
    Quisque ac diam a nunc accumsan tristique. Praesent lectus. Curabitur imperdiet est pulvinar mauris. Vestibulum leo urna, varius sit amet, ullamcorper in, ultrices eu, dolor. Integer felis diam, mattis a, tincidunt in, consectetuer ut, sapien. Sed venenatis rhoncus velit. Nulla facilisi. Duis nec elit fringilla sem viverra gravida. Cras vitae sem euismod arcu luctus pellentesque. Cras posuere nonummy felis. Nullam fermentum lacus. Vivamus mi tellus, faucibus ut, molestie et, sollicitudin non, eros. Donec imperdiet ante ac diam. Fusce eu eros. Pellentesque tortor. Phasellus sed erat eu est malesuada bibendum.
    
    Aenean dictum. Proin et quam. Curabitur pulvinar pretium tortor. In hac habitasse platea dictumst. Nunc faucibus. Fusce fringilla, magna a dignissim vestibulum, ipsum dolor ornare velit, id fermentum neque ante non odio. Morbi blandit dictum dui. Nam risus enim, aliquam sit amet, interdum eget, ullamcorper vitae, nibh. Vivamus enim libero, luctus vitae, tempus eget, tristique et, tortor. Donec magna mi, tincidunt eu, posuere vel, vulputate eu, mi. Nulla at ante vitae est pulvinar faucibus. Nullam pretium. Phasellus velit mauris, varius in, dapibus et, tempor non, quam. Nam eget augue nec est tempor semper. Vivamus eleifend tortor in tellus. Pellentesque ultricies dui sit amet erat. Quisque non tellus pellentesque arcu porttitor ultrices. Aenean faucibus vehicula odio. Donec sed velit.
    
    Nam malesuada justo ut arcu pellentesque mattis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras nec urna sed nunc posuere tincidunt. Nullam sollicitudin, tellus mollis congue porta, nisl ipsum tempor ante, nec sagittis turpis dui in enim. Nullam consectetuer luctus orci. Sed mattis vehicula elit. Nam venenatis odio sit amet metus. Duis quis nunc. Proin egestas augue in nisl. Aliquam vulputate quam. Vestibulum iaculis volutpat nunc. Fusce pharetra. Aliquam malesuada sem nec lectus volutpat ornare. Aliquam id diam eget pede lacinia nonummy. Sed neque massa, porta at, dictum sit amet, pharetra vitae, metus. Aenean quis ligula non enim varius rutrum. Suspendisse ipsum erat, convallis non, mattis pulvinar, interdum a, lacus. Duis consectetuer purus ac nunc. Fusce non nibh nec massa congue porttitor. Etiam vestibulum, diam eu mollis dignissim, justo massa nonummy sem, volutpat consequat nulla tellus id ipsum.
    
    Praesent ullamcorper, metus et placerat suscipit, ante nunc suscipit dui, in auctor justo pede nec ipsum. Nullam quis diam. Vestibulum commodo lacus eu arcu. Suspendisse potenti. Vestibulum arcu. Aliquam nonummy metus vel neque. In pellentesque interdum ligula. Aliquam erat volutpat. Cras tortor nibh, lobortis quis, egestas in, pharetra ullamcorper, sem. Aenean ultricies nulla id lacus. Vestibulum massa erat, scelerisque et, tincidunt sit amet, ultricies a, ipsum. Donec quam purus, eleifend ac, vulputate sed, auctor sit amet, tellus.
    This is what I get when I compile:
    Code:
    jshao@MCP ~/Programming/C++/test $ g++ test.cpp -Wall -W -ansi -pedantic -o test.exe
    test.cpp: In function `void Survival_of_the_Fittest()':
    test.cpp:20: warning: unused variable `int exit'
    test.cpp: In function `void Copyfrom(std::basic_string<char,
       std::char_traits<char>, std::allocator<char> >, std::basic_string<char,
       std::char_traits<char>, std::allocator<char> >)':
    test.cpp:80: warning: unused variable `int from_length'
    and this is what I get when I run:
    Code:
    jshao@MCP ~/Programming/C++/test $ ./test.exe
    The number correct is: 0
    I suggest you post more code and your files, because there's just waaay too much that can be wrong at this point.

    and wtf does "then we have to randomly regenerate exactly same content." mean?

    edit: oh yeah, and assert() is yucky... handle the errors in your own way
    Last edited by major_small; 03-22-2006 at 11:54 PM.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    57
    Well the "then we have to randomly regenerate exactly same content." means that we have to creat another .txt file and keep generating untill the file we creat is exactly the same. And for the code thats the only to function used the rest is main function calling it. So there is nothing else. And thanks for trying. Gota bug the teacher tommorow.

  4. #4
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    Quote Originally Posted by kennny2004
    Well the "then we have to randomly regenerate exactly same content." means that we have to creat another .txt file and keep generating untill the file we creat is exactly the same. And for the code thats the only to function used the rest is main function calling it. So there is nothing else. And thanks for trying. Gota bug the teacher tommorow.
    so the code I have is the same code you have? if so, just show me your input files... I can probably help you fix it. and for the record, that is the most insanely useless project I have ever heard of. Unless of course you're doing some kind of research into the PRNG...

    Okay, I almost did your homework for you. It looks like you needed to time your code, and I didn't do that. All I did was count the number of iterations of the interior loop it took to get the file right. I also didn't throw in any checks, so if the files don't open, it won't really tell you what's wrong.

    And I'm pretty sure that if you used this code your professor will know it's not your own... I passed streams between functions, and it doesn't look like you're up to that level yet

    Code:
    #include <iostream>
    #include <fstream>
    #include <ctime>
    #include <cstdlib>
    
    long int copy(std::fstream&in, std::fstream&out);
    bool check(std::fstream&orig, std::fstream&copy);
    
    int main()
    {
    	srand(static_cast<unsigned int>(time(0)));
    	
    	std::fstream in("test.in",std::ios::in);
    	std::fstream out("test.out",std::ios::out|std::ios::trunc);
    
    	long int iter=copy(in,out);
    
    	in.close();
    	in.clear();
    	in.open("test.in",std::ios::in);
    	out.close();
    	out.clear();
    	out.open("test.out",std::ios::in);
    
    	if(check(in,out))
    	{
    		std::cout<<"Files Successfully Copied in "<<iter<<" iterations"
    			<<std::endl;
    	}
    	else
    	{
    		std::cout<<"Error in File Copy"<<std::endl;
    	}
    
    	in.close();
    	out.close();
    
    	return 0;
    }
    
    long int copy(std::fstream&in, std::fstream&out)
    {
    	char ch;
    	char ch2;
    	long int iter=0;
    	
    	while(in.get(ch))
    	{
    		do
    		{
    			ch2=static_cast<char>(rand());
    			iter++;
    		}
    		while(ch2!=ch);
    		out<<ch2;
    	}
    
    	return iter;
    }
    
    bool check(std::fstream&orig,std::fstream&copy)
    {
    	char ch;
    	char ch2;
    	
    	while(orig.get(ch) && copy.get(ch2))
    	{
    		if(ch!=ch2)
    		{
    			return false;
    		}
    	}
    	return true;
    }
    it also doesn't print the file out to standard output. So why did I even do it? So you can read it and learn the algorithm, which is where I suspect you're having the problem... So I leave it to you.

    oh yeah, and there's no comments
    Last edited by major_small; 03-23-2006 at 01:09 AM.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  5. #5
    Registered User
    Join Date
    Sep 2005
    Posts
    57
    OO Wow thanks for that I will check and see what i did wrong and try to get something out of your code. And once again thanks for the time and all the help. I am almost there But not yet. Thanks Once again.

    K after looking at it for an hour All i can say is . I am so confused not funny one thing is don't u need to create another file for the to copy to to avoid trncation. And umm why don't u used using namespace std; Just our of curiosity. Does it make it slower or anything?. Thanks
    Last edited by kennny2004; 03-23-2006 at 12:43 PM.

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by kennny2004
    And umm why don't u used using namespace std; Just our of curiosity. Does it make it slower or anything?. Thanks
    It unnecessarily pollutes the global namespace with a lot of useless crap. For small programming projects it doesn't hurt by having "using namespace std" in the code. For larger projects there is a greater likelihood for object naming conflicts and you should do without it. Overall, you should try to avoid it where possible.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  7. #7
    Registered User
    Join Date
    Sep 2005
    Posts
    57
    Hey thanks for responce and umm u can use file.get(ch); for writing 2?
    Never knew that.

  8. #8
    Registered User
    Join Date
    Sep 2005
    Posts
    57
    Hmm so how come is that so fast lol. Everyone that made it in class is so much slower and since i kinda used ur alcagorithm It works so fast lol i thought generating the whole file random then going over it regenerating them random again but the ones that are right chars don't touch them be faster cause you do more at once.

  9. #9
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    because reading and writing takes a long time.

    Think about it this way - every time you change something in a file, you're telling your processor to send something to your harddrive, which has to find the bit on the disk, physically move to it, and change it. if you do it the way I did it, the processor just changes a bit in memory, and the writing is done later on.

    you're also thrashing your disks your way - a whole lot of unessecary reading/writing in the same place, which wears your disks down and actually shortens the life a little.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Homework
    By kermi3 in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 11-03-2001, 04:39 PM
  2. Homework
    By kermi3 in forum C++ Programming
    Replies: 15
    Last Post: 09-26-2001, 03:16 PM
  3. Homework
    By kermi3 in forum Windows Programming
    Replies: 5
    Last Post: 09-15-2001, 11:48 AM
  4. Homework
    By kermi3 in forum C Programming
    Replies: 0
    Last Post: 09-10-2001, 01:26 PM