C++ program to shuffle words of each line of the given file














































C++ program to shuffle words of each line of the given file



/*
Description: We have to read a file and shuffle the words of each line. We just have to store the contents of each line in a vector and shuffle it.
After each step we need to clear the contents of the vector to store the words of next line of the file.
Steps:-
1)First we read each line of the file named input.txt. We also created a file named temp.txt
2)After reading one line at a time, we split it into words and store them in a vector declared globally
3)Then we iterate over the vector and write the contents in the file named temp.txt. Then we clear the contents of vector to store next line into it
4)We repeat the steps 2 & 3 till all lines in the file are read and shuffled.
5)Now our temp file contains the shuffled lines.
6)We remove the input.txt file and rename temp.txt to input.txt.
*/


#include<bits/stdc++.h>
using namespace std;

vector<string>vec;

/* Function to split a line read from file into words and storing them in a vector*/
void pushIntoVector(string str)
{
string word ="";
for(auto x:str)
{
if(x==' ')
{
vec.push_back(word);
word="";
}
else
{
word=word+x;
}
}
vec.push_back(word);
}

int main()
{
  fstream inputFile("input.txt");
  fstream tempFile("temp.txt",fstream::out);
  string line;

  while(getline(inputFile,line))
  {
    vec.clear();
vec.shrink_to_fit();
    pushIntoVector(line);
default_random_engine dre(std::chrono::system_clock::now().time_since_epoch().count());
   shuffle(vec.begin(),vec.end(),dre);
for(int i=0;i<vec.size()-1;i++)
{
tempFile<<vec[i]<<" ";
}
tempFile<<vec[vec.size()-1]<<"\n";
  }
inputFile.close();
remove("input.txt");
rename("temp.txt","input.txt");
tempFile.close();
}



  /* Input
  Love For All, Hatred For None
  Never regret anything that made you smile
  Problems are not stop signs, they are guidelines
  Life is really simple, but we insist on making it complicated
  Eat sleep code repeat

    Output
  All, Love None Hatred For For
  smile regret Never anything you made that
  Problems they not signs, guidelines are are stop
  making simple, on Life we complicated it insist but really is
  code repeat Eat sleep 
*/


Comments